#coding:utf8
from flask_restful import  Resource,fields, marshal_with
from flask import request,abort,session
from common import token as tken,app_setting,sms_send,wx_op
from db_base.TournamentServer import Tournament,TM
from common.getallgametype import *
from common.base import *
import datetime
import uuid
import sys
import base64
import requests
import hashlib
reload(sys)
import json
import random
sys.setdefaultencoding('utf-8')
from mg_config import yz_log


class UserAPI(Resource):
	## 获取用户信息
    def get(self):
    	user_id  = request.values.get('user_id')
        ip =request.remote_addr
        ## 先查找用户
        user_data = dict()
        auto_datas = TM.getByfilter('user_auths',dict(user_id = user_id,status = '\x00'))
        for auto in auto_datas:
            identity_type=auto.get('identity_type')
            if identity_type!='phone':
                user_data[identity_type] = 1
            else:
                user_data[identity_type] = auto.get('identifier')
    	## 查询用户
    	token = tken.generate_auth_token(user_id)
        return dict(user_id = user_id,token = token)
    ## 注册登陆
    def post(self):
    	query = request.json
    	user_name = query.get('user_name')
    	passwd = query.get('passwd')
        ## 用户来源微信/qq/贴吧第三方登陆
    	if user_name is None:
    		return dict(code = 30001,msg  = '填写用户名')
    	if passwd is None:
    		return dict(code = 30002, msg  = '输入密码')

    	return dict(user_id = 1,token = tken.generate_auth_token(1))
    ## 更新用户信息
    def put(self):
        query = request.json
        user_id = query.get('user_id')
        token   =query.get("token")
        if not user_id or not token or not tken.verify_auth_token(token) or int(user_id)!=int(tken.verify_auth_token(token).get("id")):
            return dict(code= 1, msg = '请登陆')

        user_d = TM.select("users",dict(id = int(user_id)))
        if not user_d:
            return dict(code= 30005, msg = '账号不存在')

        if user_d.get("status")=='\x01':
            return dict(code = 30006, msg  = '账号被封禁')
        gender = query.get("gender","")
        nickname = query.get("nickname","")
        addr  = query.get("address","")
        v_data  = dict()
        if gender!="":
            v_data['gender'] = '\x01' if gender==1 else '\x00'
        if nickname:
            v_data['nickname']  = nickname
        if addr:
            v_data['addr'] = addr
        if not v_data:
            return dict(code= 30006, msg = '没有发生变化')
        TM.update("users",v_data, dict(id =user_d.get("id") ))
        return dict(code = 0 ,msg= '修改成功')
        ## 可以根据用户的id来查找token是否过期，过期就修改失败

    ## 删除用户信息
    def delete(self):

        pass

class regist(Resource):
    def post(self):
        ## 用户注册
        ## 根绝类型来判断如何注册例如:type为phone
        ##  目前只有第三方授权登陆
        query  = request.json
        _type = query.get('type')
        code= query.get("code")
        if not code or code =='null':
            return dict(code= 1, msg ='授权失败')
        # if _type == 'phone':
        ip =  request.headers['X-Forwarded-For']
        ip = ip.split(',')[0]
        #     pass
        if _type =='wx' or _type =='wxpc':
            ## 微信授权接口

            try:
                wx_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx2535ac9f0488e2bf&secret=81f8fd00417f6458bd0d8db010950f0a&code="+code+"&grant_type=authorization_code"
                if _type=='wxpc':
                    wx_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxf4537cea28c4fce7&secret=5cafe79a3e4aa4311ad56f924b0e1d27&code="+code+"&grant_type=authorization_code"
                response  = requests.get(wx_url)
                content = json.loads(response.content)
                #用户的access_token
                access_token = content.get("access_token")
                #用户wx的openid
                openid = content.get("openid")

            except Exception as e:
                yz_log.error(str(e))


            try:
                response = requests.get("https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid)
                content = json.loads(response.content)
                #wx的nick_name
                nick_name = content.get("nickname")
                unionid = content.get("unionid")
                WX_d = TM.select('user_auths',dict(identity_type='wx',
                identifier = unionid))

                #用户wx的headimgurl
                headimgurl = content.get("headimgurl")
                headimgurl = headimgurl.replace("\/","/")
                #用户wx的性别 (0表示女，1表示男)
                sex = content.get("sex")
                if sex==0:
                    sex = b'\x01'
                else:
                    sex =b'\x00'
                if WX_d:
                    user_id = WX_d.get('user_id')
                    TM.update("user_auths",dict(nickname = nick_name, credential = access_token),dict(id = WX_d.get("id")))
                    TM.add('login_record',dict(user_id = user_id, ip = ip,
                            create_time = datetime.datetime.now()))
                    return dict(code  = 0, user_id = user_id,
                            token = tken.generate_auth_token(int(user_id)))

                response = requests.get(headimgurl)
                image_content = response.content
                key = str(md5_value(image_content)) + '.jpg'
                ret = upload_file(image_content, key)
                last_id = TM.add('users',dict(create_time = datetime.datetime.now(),
                                                nickname = nick_name,
                                                icon = key,
                                                gender =sex
                    ))
                if last_id:
                    _id =  TM.add('user_auths',dict(create_time = datetime.datetime.now(),
                                            user_id = last_id,
                                            identity_type = 'wx',
                                            identifier = unionid,
                                            nickname = nick_name,
                                            credential = access_token
                        ))
                    TM.add('login_record',dict(user_id = last_id, ip = ip,
                            create_time = datetime.datetime.now()))                   
                    return dict(code  = 0, user_id = last_id,
                    token = tken.generate_auth_token(last_id))                

            except Exception as e:
                yz_log.error(str(e))
        elif _type =='qq':
            if query.get("code") != "null":
                code = query.get("code")
                try:
                    response  = requests.get("https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=101485201&client_secret=2faed734e5bdfe0ca810ca4349e0ba6d&code="+code+"&redirect_uri=http%3a%2f%2fgzb.dev-juyouxiao.com%3a9088%2findex.html")
                    content = response.content.decode("utf-8")
                    content = content.split("&",1)
                    content = content[0].split("=",1)
                    #用户的access_token
                    access_token = content[1]
                except Exception as e:
                    yz_log.error(str(e))
                    return dict(status=1,msg=str(e))

                try:
                    response = requests.get("https://graph.qq.com/oauth2.0/me?access_token="+access_token)
                    content = response.content.decode("utf-8")
                    content = content.split('"openid":"',1)
                    content = content[1].split('"}',1)

                    #用户QQ的openid
                    openid = content[0]
                except Exception as e:
                    yz_log.error(str(e))
                    return dict(status=1,msg=str(e))
                try:
                    ## 查找是否已经登录
                    QQ_d = TM.select('user_auths',dict(identity_type='qq',
                        identifier = openid))
                    response = requests.get("https://graph.qq.com/user/get_user_info?access_token="+access_token+"&oauth_consumer_key=101485201&openid="+openid)
                    content = response.content.decode("utf-8")
                    content  = eval(content)
                    #用户QQ的nickname
                    nickname = content.get("nickname")
                    #用户QQ的sex(返回"男"或者"女")
                    gender = b'\x00'
                    sex = content.get("gender")
                    if sex=='女':
                        gender =b'\x01'
                    #用户QQ的headimgurl
                    headimgurl = content.get("figureurl_2")
                    headimgurl = headimgurl.replace("\/","/")
                    if not QQ_d:
                        response = requests.get(headimgurl)
                        image_content = response.content
                        key = str(md5_value(image_content)) + '.jpg'
                        ret = upload_file(image_content, key)

                        last_id = TM.add('users',dict(create_time = datetime.datetime.now(),
                                                        nickname = nickname,
                                                        icon = key,
                                                        gender = gender
                            ))
                        if last_id:
                            _id =  TM.add('user_auths',dict(create_time = datetime.datetime.now(),
                                                    user_id = last_id,
                                                    identity_type = 'qq',
                                                    identifier = openid,
                                                    nickname = nickname,
                                                    credential = access_token
                                ))
                            TM.add('login_record',dict(user_id = last_id, ip = ip,
                                create_time = datetime.datetime.now()))
                            return dict(code  = 0, user_id = last_id,
                            token = tken.generate_auth_token(last_id))

                    else:
                        TM.add('login_record',dict(user_id = QQ_d.get('user_id'), ip = ip,
                            create_time = datetime.datetime.now()))
                        TM.update("user_auths",dict(nickname = nickname, credential = access_token),dict(id = QQ_d.get("id")))
                        return dict(code  = 0, user_id = QQ_d.get('user_id'),
                            token = tken.generate_auth_token(int(QQ_d.get('user_id'))))
                except Exception as e:
                    yz_log.error(str(e))
                    return dict(status=1,msg=str(e))


            else :
                return dict(status=1,msg="获取不到code")
        elif _type =='baidu':
            yz_log.info(query)
            if query.get("code") != "null":
                code = query.get("code")
            try:
                response = requests.get("https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&client_id=BaqV85SxU8ub0YmfxXmAoi6X&client_secret=hlUzDxcY4GqjEa9k8NCfrbzYvh1n8ML8&code="+code+"&redirect_uri=http%3a%2f%2fgzb.dev-juyouxiao.com%3a9088%2findex.html")
                content = json.loads(response.content)
                
                #用户的access_token
                access_token = content.get("access_token") 
            except Exception as e:
                yz_log.error(str(e))
                return dict(status=1,msg=str(e))

            try:
                
                response = requests.get("https://openapi.baidu.com/rest/2.0/passport/users/getInfo?access_token="+access_token)
                content = json.loads(response.content)
                #用户的userid
                userid = content.get("userid")
                #用户的username
                username = content.get("username")
                #用户的headimgurl
                headimgurl = "http://tb.himg.baidu.com/sys/portrait/item/"+content.get("portrait")
                #用户的sex(返回0或者1,0代表女，1代表男)
                sex = content.get("sex")

                ## 查看是否已经授权登陆过
                baidu_d = TM.select("user_auths", dict(identity_type = 'tieba', identifier = userid))
                if not baidu_d:
                    response = requests.get(headimgurl)
                    image_content = response.content
                    key = str(md5_value(image_content)) + '.jpg'
                    ret = upload_file(image_content, key)
                    last_id = TM.add('users',dict(create_time = datetime.datetime.now(),
                                                    nickname = username,
                                                    icon = key,
                                                    gender =b'\x00' if sex==1 else b'\x01'
                        ))
                    if last_id:
                        _id =  TM.add('user_auths',dict(create_time = datetime.datetime.now(),
                                                user_id = last_id,
                                                identity_type = 'tieba',
                                                identifier = userid,
                                                nickname = username,
                                                credential = access_token
                            ))
                        TM.add('login_record',dict(user_id = last_id, ip = ip,
                            create_time = datetime.datetime.now()))
                        return dict(code  = 0, user_id = last_id,
                        token = tken.generate_auth_token(last_id))
                else:
                    TM.add('login_record',dict(user_id = baidu_d.get('user_id'), ip = ip,
                            create_time = datetime.datetime.now()))
                    TM.update("user_auths", dict(nickname = username, credential = access_token), dict(id = baidu_d.get('id')))
                    return dict(code  = 0, user_id = baidu_d.get('user_id'),
                        token = tken.generate_auth_token(int(baidu_d.get('user_id'))))                                
            except Exception as e:
                yz_log.error(str(e))
                return dict(status=1,msg=str(e))

        return dict(code =1, msg  = '未知登陆')

## 赛事类型
class tournament(Resource):

    def get(self):
        # token =  request.values.get('token')
        query = request.values
        _type = query.get('type')
        offset = query.get('offset',0)
        limit = query.get('limit',3)
        params = dict()
        if _type:
            params['type'] = _type
        hot_status = query.get('hot_status',1)
        if hot_status:
            params['hot_status'] = hot_status
        event =  TM.getByfilter('hot_event',params,offset = int(offset), limit = int(limit),order = ' order by id desc ')
        games =  TM.getByfilter('events_type',dict())
        game_type = TM.getByfilter('game',dict())
        game_dict = dict()
        type_dict  = dict()
        for _game in game_type:
            game_dict[_game.get('id')] = _game.get('game_name')
        for _game in games:
            type_dict[_game.get('id')] = _game.get('type_name')
        # data = tken.verify_auth_token(token)
        datas = []
        for _event in event:
            _now = datetime.datetime.now()
            apply_start_time = _event.get('apply_start_time')
            apply_end_time = _event.get('apply_end_time')
            status = deal_time_for_event_s(apply_start_time, apply_end_time, _event.get('game_start_time'), _event.get('game_end_time'))
            apply_time = apply_start_time.strftime('%Y.%m.%d')+\
            '-' +_event.get('apply_end_time').strftime('%Y.%m.%d')
            _game_type = _event.get('game_type',1)
            game_name = game_dict.get(_game_type,str(_game_type))
            datas.append(dict(
                        events_title= _event.get('events_title',''),
                        game_name = game_name,
                        # type = _event.get('type',1),
                        # event_details = _event.get('event_details',''),
                        total_bonus= _event.get('total_bonus',0),
                        apply_time = apply_time,
                        has_team = _event.get('has_teams',0),
                        max_team = _event.get('max_teams',0),
                        status = status, ## 赛事描述
                        icon = app_setting.QINIUHOST+_event.get('icon'),
                        event_type_name =  type_dict.get(_event.get('event_type_id'),str(_event.get('event_type_id'))),
                        id = _event.get('id'),
                        award_type = _event.get('award_type'),
                        award_name = _event.get('award_name',''),
                        apply_start_time = apply_start_time.strftime('%Y-%m-%d %H:%M:%S'),
                        apply_end_time =apply_end_time.strftime('%Y-%m-%d %H:%M:%S'),
                        type = event_num(status)
                ))
        return dict(datas = sorted(datas, key=lambda x : x['type'], reverse=False),code  = 0)

    def post(self):
        ## 赛事类型
        ## 报名赛事  操作者id，赛事id#####
        ## 战队赛的话要参加的成员id
        query = request.json
        user_id = query.get('user_id',0)
        event_id = query.get('event_id',0)
        user_list = query.get('u_l',[]) ## 
        token = query.get('token','')
        if not user_id or not token or not tken.verify_auth_token(token) or int(user_id)!=int(tken.verify_auth_token(token).get('id')):
            return dict(code = 1, msg = '请登陆')
        if not isinstance(user_list, list):
            return dict(code= 30005, msg ='参数错误') 


        ## 根据赛事id来查找每个队伍必须参数的人数
        ### 查看当前报名用户是否有权限报名比赛
        event_type_d = GetEventType()
        ## event_datas
        event_datas = TM.select('hot_event',dict(id  = event_id))
        if not event_datas:
            return dict(code = 30005, msg = '赛事不存在')
        if event_datas.get('apply_end_time')<=datetime.datetime.now():
            return dict(code = 30006, msg = '赛事已结束报名')
        team_num = event_datas.get('team_num',0)
        has_teams = event_datas.get('has_teams')
        if event_type_d.get(event_datas.get('event_type_id'),None)==u'战队赛' and len(user_list)!=event_datas.get('team_num',0):
            return dict(code = 30005, msg = '每个参赛队伍人数为%s'% team_num)
        if has_teams>=event_datas.get('max_teams'):
            return dict(code =30009, msg = '参赛队伍已达上限')


        team_d = TM.select('game_team', dict(team_leader_id = user_id), field = [' id '])
        team_id = team_d.get('id')
        user_team_data = TM.getByfilter('user_team',dict(
            user_id = user_id,team_id  = team_id))
        if not user_team_data or user_team_data[0].get('team_position',0)==0:
            return dict(code= 30005,msg = '没有操作权限')

        ## 限制每人只能报名一次

        check_data = TM.getByfilter('auth_event',dict(user_id  = user_id, event_id = event_id,status = '\x00'))
        if check_data:
            return dict(code = 30006,msg = '请勿重复报名')
        if team_num > 1:
            if TM.getByfilter('auth_event',dict(user_id  = user_id, event_id = event_id,status = '\x00')):
                return dict(code= 1 , msg = '已有其他成员报名了该赛事!')

        last_id = TM.add('auth_event',dict(
                                event_id = event_id,
                                user_id = user_id,
                                team_id = team_id,
                                create_time = datetime.datetime.now()
            ))


        if  last_id:
            sql_list = []
            sql_list.append(TM.update_sql('hot_event',dict(has_teams  = has_teams +1),dict(id =event_datas.get('id') )))
            for _user_id in user_list:
                sql_list.append(TM.insert_sql('auth_event_to_user',dict(
                                                auto_event_id = last_id,
                                                user_id = _user_id,
                                                event_id = event_id,
                                                create_time = datetime.datetime.now()
                    )))
            sus = TM.trance(sql_list)
            if sus:
                return dict(code = 1,msg = '报名成功',token = token)
        return dict(code = 0,msg = '报名失败')

    def put(self):
        ## 取消当前报名或者变更队友
        query = request.json
        user_id = query.get('user_id',0)
        team_id = query.get('team_id',0)
        auto_event_id = query.get('auto_event_id',0)
        status =  query.get('status',0)
        if not int(user_id) or not int(team_id) or not int(auto_event_id):
            return dict(code = 30007,msg = '非法操作')
        TM = Tournament()
        user_team_data = TM.getByfilter('user_team',dict(
            user_id = user_id,team_id  = team_id))
        if not user_team_data or user_team_data[0].get('team_position',0)==0:
            return dict(code= 30005,msg = '没有操作权限')
        if status:
            # TM.update('')
            pass



## 战队类
class GameTeam(Resource):
    def get(self):
        ## 根据战队id来获取战队信息
        params   = dict()
        query = request.values
        team_name =  query.get('team_name')
        game_id = query.get('game_id')
        _type = query.get("type","")
        if team_name:
            params['team_name'] = team_name
        if game_id:
            params['game_id'] = game_id
        params['_type']  =_type
        offset = int(query.get('offset',0))
        limit = int(query.get('limit',10))
        datas = []
        team_datas,total  = TM.GetGameTeam(params,int(offset),int(limit))
        for team in team_datas:
            _id = team.get('id')
            recruit = 0
            if team.get('recruit','\x00') =='\x01':
                recruit = 1
            max_member = team.get('max_member')
            has_member = team.get('has_member',1)
            if has_member ==max_member:
                recruit = 1
            join_game_num=team.get('join_game_num')
            competition_point=team.get('competition_point')
            team_type = team.get('team_type')
            offset +=1
            data = dict(
                        team_name= team.get('team_name',''),
                        team_icon = app_setting.QINIUHOST + team.get('team_icon',''),
                        recruit = recruit,
                        has_member = has_member,
                        join_game_num = int(join_game_num) if join_game_num else 0,
                        competition_point = int(competition_point) if competition_point else 0,
                        team_type = getTeamType().get(team_type,str(team_type)),
                        team_id = _id,
                        rank = offset,
                        max_member  = max_member

                )
            data['icon_urls'] = []
            goodgameicons = TM.getteamgoodgame(_id)
            for _ggicon in goodgameicons:
                data.get('icon_urls').append(app_setting.QINIUHOST+_ggicon.get('icon'))
            datas.append(data)
        return dict(code =0 ,datas = datas,total = total[0].get('count',0),
            data_update_time = datetime.datetime.now().strftime("%Y-%m-%d %M:%H:%S"))

    def post(self):
        ## 创建战队接口
        try:
            query = request.json
            image = query.get('team_icon','')
            user_id = query.get('user_id',0)
            token  = query.get('token','')
            get_token = tken.verify_auth_token(token)
            if not get_token or int(get_token.get('id'))!=int(user_id):
                return dict(code = 40009,msg = '请登陆')
            _type = image[:image.find(';')]

            imagename = _type[_type.find('/')+1:]
            imagename ='jpg'
            image_content = image[image.find(',')+1:]
            image_content = base64.b64decode(image_content)
            team_name   = query.get('team_name')
            if not team_name:
                # abort(400)
                return dict(code = 1 ,msg = '请填写战队名称')
            if imagename not in app_setting.IMAGEFORMAT:
                return dict(code= 30005, msg ='图片格式不对')

            key = str(md5_value(image_content)) + '.'+imagename
            ret = upload_file(image_content, key)
            if not ret:
                return dict(code=30005, msg = '图片识别错误，请重试')
            ## 查找用户信息，核实该用户是否具备创建战队的条件

            # 查找用户是否存在战队
            user_team_d = TM.getByfilter('user_team',dict(user_id = user_id))
            if user_team_d:
                return dict(code = 1, msg = '已有战队')
            team_type =query.get('team_type','电竞战队') ## 战队类型的id
            TT_d = TM.select('team_type',dict(t_type = team_type))
            if TT_d:
                team_type  = TT_d.get('id')
            else:
                team_type = 2

            if team_type==1:
                ## 判断是否具备创建贴吧战队的权限
                auto_data = TM.getByfilter('user_auths',dict(
                    user_id =user_id,identity_type = 'tieba',status =0))
                if not auto_data:
                    return dict(code = 30005,msg  = '不是吧主没有权限创建贴吧战队，请选择创建电竞战队')



            has_member = 1
            team_details = query.get('team_details') 
            if TM.getByfilter('game_team',dict(team_name = team_name)):
                return dict(code = 1,msg = '申请的战队名称冲突')
            last_id = TM.add('game_team',dict(
                                team_leader_id = user_id,
                                team_details = team_details,
                                team_icon = key,
                                team_name = team_name,
                                has_member =has_member,
                                team_type = team_type,
                                create_time  = datetime.datetime.now(),
                                check_status = 1
                ))
            if last_id:
                if TM.add('user_team',dict(
                    user_id = user_id,
                    team_id = last_id,
                    team_position = 2,
                    create_time = datetime.datetime.now()
                    )):
                    return dict(code = 0, msg = '创建成功', datas = dict(team_id = last_id, 
                        team_icon = app_setting.QINIUHOST + key))
            return dict(code = 1 ,msg = '创建失败')
            pass
        except Exception as e:
            return dict(code= 5999, msg = str(e))


    def put(self):
        ## 战队招募是否开关
        query = request.json

        token = query.get("token")
        user_id = query.get('user_id',0)
        recruit= query.get('recruit',0)
        try:
            user_id = int(user_id)
            recruit = int(recruit)
        except Exception as e:
            return dict(code = 30005 ,msg = '参数错误')

        if not user_id or not token or not tken.verify_auth_token(token) or user_id!=int(tken.verify_auth_token(token).get('id')):
            return dict(code = 30006, msg = '请登陆')
        u_t_d = TM.select('game_team', dict(team_leader_id = user_id), field = [' id '])
        msg = '招募关闭成功'
        if recruit==0:
            msg = '招募开启成功'
        if u_t_d:
            TM.update("game_team" , dict(recruit = recruit), dict(id = u_t_d.get('id')))
            return dict(code=0, msg = msg)
        return dict(code = 30003, msg = '设置失败')
        ##  

    def delete(self):
        pass
        ## 删除战队接口，就是战队的解散
        query = request.json

        user_id = query.get('user_id')
        team_id = query.get('team_id')
        ## 判断操作者是否有权操作该战队，例如：解散战队，设置战队是否对外开放招募

        token = query.get('token')
        if not user_id or not token or not tken.verify_auth_token(token) or int(user_id)!=tken.verify_auth_token('token').get('id'):
            return dict(code= 1, ms= '请登陆') 
        data = TM.getByfilter('game_team',dict(id = team_id))
        if not data:
            return dict(code = 30009,msg = '非法操作')
        if data and  data[0].get('team_leader_id')==user_id:
            ## 根据id删除战队表，根据战队id删除战队跟用户的关联表 
            delete_flag = TM.delete('game_team',dict(id = team_id))
            if delete_flag:
                return dict(code = 0,msg = '成功解散')
            else:
                return dict(code = 0,msg = '操作失败')
        return dict(code = 30005,msg = '没有操作权限')


## 参赛游戏

class Game(Resource):
    ## 获取游戏
    def get(self):
        try:
            ## 获取所有参赛游戏
            query  = request.values
            offset = query.get('offset',0)
            limit  = query.get('limit',10)
            game_datas = TM.getByfilter('game',dict(delete_flag =0),
                offset = int(offset), limit = int(limit),order = ' order by id desc ')
            datas = []
            for _game in game_datas:
                datas.append(dict(
                            game_name = _game.get('game_name',''),
                            tieba_url = _game.get('tieba_url',''),
                            id = _game.get('id',0),
                            icon =app_setting.QINIUHOST +  _game.get('icon','')
                    ))
            return dict(data = datas, code = 0)
        except Exception as e:
            return dict(code = 1, msg = str(e))
    def post(self):
        ## 添加参赛游戏
        ## 验证地址
        ## 验证游戏是否已经被添加过
        try:
            query = request.form
            game_load_url = query.get('game_load_url')
            tieba_url  = query.get('tieba_url')
            # icon = query.get('icon')
            game_name = query.get('game_name')
            ## 获取图标
            game_icon = request.files.get('icon')
            if not game_name:
                return dict(code= 1,msg = '填写游戏名称')
            ## 需要向游戏公司申请开房间和请求比赛结果的地址
            if TM.getByfilter('game',dict(game_name = game_name)):
                return dict(code = 2,msg = '游戏已经存在，可前往修改信息')

            image_content = game_icon.read()

            imagename =game_icon.filename
            if imagename.split('.')[1] not in app_setting.IMAGEFORMAT:
                return dict(code= 30005, msg ='图片格式不对')

            key = str(md5_value(image_content)) + imagename
            ret = upload_file(image_content, key)
            if not ret:
                return dict(code=30005, msg = '图片识别错误，请重试')
            last_id = TM.add('game',dict(
                    tieba_url = tieba_url,
                    game_load_url = game_load_url,
                    icon = key,
                    game_name = game_name,
                    create_time = datetime.datetime.now()
                ))
            if last_id:
                return dict(code = 0, msg = '添加成功')
            return dict(code =1, msg = '添加游戏失败')
        except Exception as e:
            return dict(code=0,msg = str(e))


    def put(self):
        ## 更新参赛游戏信息
        ## game_id 需要修改的字段
        query = request.json
        game_id = query.get('id')
        if  not game_id:
            return dict(code = 4 ,msg = '操作错误')
        game_name  =  query.get('game_name')
        delete_flag = query.get('delete_flag')
        if TM.getByfilter('game',dict(game_name = game_name)):
            return dict(code = 1, msg ='名称冲突')
        status = TM.update('game',dict(game_name = game_name),dict(id = game_id))
        if status:
            return dict(code = 0,msg = '修改成功')
        return dict(code = 0, msg = '修改失败')

    def delete(self):
        ## 删除参赛游戏
        query = request.json
        game_id = query.get('game_id')
        if not game_id:
            return dict(code=  1, msg = '操作错误')

        delete_flag = TM.update('game',dict(delete_flag = '\001'),dict(id = game_id))

## 战队报名参加比赛的类
class TeamJoinGame(Resource):

    def get(self):
        ## 验证报名权限
        ## 获取可报名参赛的成员信息 user_id，user_icon
        query = request.values
        token = query.get('token')
        user_id = query.get('user_id',0)
        if not user_id or not token or not tken.verify_auth_token(token) or int(user_id)!=int(tken.verify_auth_token(token).get('id')):
            return dict(code= 1, msg = '请登陆')
        event_id = query.get('event_id',0)
        ## 操作者权限
        # user_se = TM.select('game_team',dict(team_leader_id = user_id), field = [ ' id '])
        # print user_se
        # if not user_se:
        #     return dict(code = 1,msg = '没有权限')

        user_team_d = TM.select('user_team', dict( user_id  = user_id), field = [' team_position,team_id '])
        if not user_team_d or user_team_d.get('team_position',0)==0:
            return dict(code = 1,msg = '没有权限')
        team_id = user_team_d.get('team_id')
        event_data =  TM.select('hot_event',dict(id = event_id))
        if not event_data:
            return dict(code = 30005,msg = '非法操作')
        game_id = event_data.get('game_id')
        datas =dict(event_name=  event_data.get('events_title',''),
                    game_name = GetGameData().get(game_id,str(game_id)),
                    event_id = event_data.get('id'),
                    team_num = event_data.get('team_num')
            )

        ## 查看已报名的人员
        applyed_d = TM.select_all('auth_event_to_user', dict(event_id = event_id), field = [ ' user_id '])
        _user_id_list = []
        for i in applyed_d:
            _user_id_list.append(i.get('user_id'))
        team_user_d = TM.GetUserToEvent(team_id)
        team_user_dict  = dict()
        user_id_list = []
        for team_user in team_user_d:
            team_user['icon'] = app_setting.QINIUHOST + team_user.get('icon')
            user_id = team_user.get('id')
            if user_id not in _user_id_list:
                user_id_list.append(user_id)
                team_user_dict[user_id] = team_user
        if not team_user_dict:
            return dict(code = 30003, msg = '没有可参赛队员')
        # is_user_d  = TM.select_all('my_game',dict(game_id  = game_id,),
        #                                in_condition = dict(user_id = tuple(user_id_list))
        #     )
        datas['user_datas'] =team_user_dict
        # datas['user_datas'] = []
        # for user_d in is_user_d:
        #     datas.get('user_datas').append(team_user_dict.get(user_d.get('user_id')))
        return dict(code = 0,datas = datas,token = token)


    def post(self):
        pass 
        ## 验证报名参赛者成员的权限

    def put(self):
        pass
        ## 修改报名信息，可取消报名，可变更报名的组成成员
    def delete(self):
        pass
        ## 

## 申请战队类
class ApplyTeam(Resource):
    ## 获取申请战队的信息
    def get(self):
        ## 战队id
        query = request.values
        team_id = query.get('team_id')
        return dict(code = 0,data = dict(team_id=  team_id))
    def post(self):
        ## 申请加入战队接口
        ## 需要请求带上token
        # print request.form
        # upload_file = request.files.get('file')

        # print upload_file.filename.split('.')
        # print request
        # return dict(code = 0,a =1)

        query = request.json
        user_id = query.get('user_id')
        team_id = query.get('team_id')
        token = query.get('token')
        detail = query.get('detail','')
        if not token or not tken.verify_auth_token(token) or int(tken.verify_auth_token(token).get('id'))!=int(user_id):
            return dict(code = 1 , msg = '请登陆')

        ## 查看战队是否存在
        isTeamD =TM.select('game_team',dict(id =team_id), field =[' team_name '])
        if not isTeamD:
            return dict(code=1 ,msg = '战队不存在')
        if TM.select('user_team',dict(user_id = user_id)):
            return dict(code=1 , msg = '已有战队')
        if TM.select('apply_team',dict(team_id = team_id, user_id = user_id,status= 0)):
            return dict(code = 1 , msg = '请勿重复申请')
        # token 解码判断是否再有效时间内，解码与user_id对比是否相等

        sql_list =[]
        sql_list.append(TM.insert_sql('apply_team',dict(user_id = user_id,team_id = team_id,
                                detail = detail,create_time  = datetime.datetime.now()
            )))
        now = datetime.datetime.now()
        message = u'于'+now.strftime("%Y-%m-%d %M:%H:%S") + u'申请  ' + isTeamD.get('team_name')
        sql_list.append(TM.insert_sql('user_message', dict(user_id = user_id,message = message,
            create_time = now)))
        if TM.trance(sql_list):
            return dict(code = 0,msg ='申请成功')
        return dict(code= 1 , msg = '申请失败')

## 个人赛事预约
class AppointmentEvent(Resource):

    def post(self):
        ## 赛事预约,需要用户登陆
        query = request.json
        user_id = query.get('user_id',0)
        event_id = query.get('event_id',0)

        try:
            user_id = int(user_id)
            event_id = int(event_id)
        except Exception as e:
            return dict(code = 1, msg  ='参数错误')
        token = query.get('token')
        if not token or not tken.verify_auth_token(token):
            return dict(code = 1, msg = '请登陆')

        user_token = tken.verify_auth_token(token)
        if int(user_token.get('id'))!=int(user_id):
            return dict(code= 1, msg = '非法操作')
        hot_event_d = TM.select('hot_event',dict(id = event_id))
        if not hot_event_d:
            return dict(code  = 1,msg = '非法操作')
        filter_params = dict(user_id = user_id,event_id = event_id)
        appointment_event_d = TM.select('appointment_event',filter_params)
        if appointment_event_d:
            if query.get('status'):
                ## 存在status 取消预约
                if TM.update('appointment_event',dict(status =1),filter_params):
                    return dict(code = 0,msg = '成功取消预约')
                return dict(code = 0,msg = '取消预约失败')
            return dict(code=0,msg = '已预约')
        filter_params['create_time'] = datetime.datetime.now()
        last_id = TM.add('appointment_event',filter_params)
        if last_id:
            return dict(code = 0, msg = '成功预约')
        return dict(code= 0,msg = '预约失败')

## 首页战队榜
class TeamPerformance(Resource):

    def get(self):
        ##获取战队榜详情 
        query = request.values
        _type = query.get('performance_type','w')
        game_id = query.get('game_id')
        offset = int(query.get('offset',0))
        limit = query.get('limit',10)
        filter_params  = dict(_type =_type)
        if game_id:
            filter_params['game_id'] = game_id
        filter_params['offset'] = int(offset)
        filter_params['limit'] = int(limit)
        datas = TM.TeamPerformanceData(filter_params)
        for data in datas:
            team_id = data.get('id')
            offset +=1
            data['rank'] = offset 
            join_game_num  = data.get('join_game_num')
            competition_point = data.get('competition_point')
            data['join_game_num'] = int(join_game_num) if join_game_num else 0 
            data['competition_point'] = int(competition_point) if competition_point else 0
            data['game_icon_urls'] = []
            data['team_icon'] = app_setting.QINIUHOST + data.get('team_icon','')
            data['team_type'] = getTeamType().get(data.get('team_type'))
            ## 查找team擅长的游戏icon_url
            goodgameicons = TM.getteamgoodgame(team_id)
            for _ggicon in goodgameicons:
                data.get('game_icon_urls').append(app_setting.QINIUHOST+_ggicon.get('icon'))
        return dict(code = 0,datas = datas,data_update_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        ## 获取所有战队榜数据

# 首页赛事榜
class EventPerformance(Resource):

    ## 
    def get(self):
        
        query =request.values
        game_id = query.get('game_id',0)
        offset = int(query.get('offset',0))
        limit  = int(query.get('limit',10))
        award_type = query.get('award_type',0)

        filter_params =dict(award_type = int(award_type))
        if game_id:
            filter_params['game_id'] = int(game_id)
        event_datas =  TM.GetEventPerformance(filter_params,offset,limit)
        datas = []
        for data in event_datas:
            has_teams = data.get('has_teams',0)
            team_num = data.get('team_num',0)
            apply_start_time = data.get('apply_start_time')
            apply_end_time  = data.get('apply_end_time')
            game_start_time = data.get('game_start_time')
            game_end_time = data.get('game_end_time')
            event_status =  deal_time_for_event_s(apply_start_time, apply_end_time, game_start_time, game_end_time)

            datas.append(dict(
                        event_title = data.get('events_title',''),
                        event_status = event_status,
                        total_bonus = data.get('total_bonus'),
                        event_type_name = GetEventType().get(data.get('event_type_id')),
                        participation = has_teams*team_num if team_num else has_teams,
                        id  =data.get('id'),
                        type = event_num(event_status),
                        has_member = data.get('has_member',0),
                        max_member= data.get('max_member',0),
                        apply_start_time = data.get('apply_start_time').strftime("%Y-%m-%d %M:%H:%S")

                ))
        return dict(code= 0,datas = sorted(datas, key=lambda x : x['type'], reverse=False),
            data_update_time = datetime.datetime.now().strftime("%Y-%m-%d %M:%H:%S"))


## 明星战队check
class StarTeam(Resource):
    def get(self):
        ## 获取明星战队信息
        star_team_d = TM.select_all('game_team',condition= dict(star_flag = 1,dissolve =0),
            field=['team_name','team_icon','team_details','has_member','id'],offset =0,limit = 8)
        for star_team in star_team_d:
            star_team['team_icon'] = app_setting.QINIUHOST + star_team.get('team_icon')
        return dict(datas = star_team_d, code = 0)


## 明星队长check
class StarTeamLeader(Resource):

    def get(self):
        ##
        start_leader_d = TM.getstarleader()
        for star in start_leader_d:
            if star.get('icon'):
                star['icon']= app_setting.QINIUHOST + star.get('icon')
            else:
                star['icon']= ''
        return dict(datas = start_leader_d, code =0)

## 获取战队类型
class TeamType(Resource):

    def get(self):
        return dict(datas = TM.select_all('team_type',condition =dict(delete_flag = 0),
            field = ['id','t_type as name']), code = 0)

## 查看战队基本信息
class CheckTeam(Resource):

    def get(self):

        query = request.values
        token = query.get('token')
        user_id = query.get('user_id')
        team_id = query.get('team_id',0)
        if token and tken.verify_auth_token(token):
            user_id = tken.verify_auth_token(token).get('id')
        try:
            team_id = int(team_id)
        except Exception as e:
            return dict(code = 1,msg= '非法操作')
        apply_team_status = 0 # 没有战队的可申请加入战队
        u_team_d  = TM.select('user_team',dict(user_id = user_id),field = [' team_id, team_position '])
        ## 
        if u_team_d and u_team_d.get('team_id')==team_id:
            ## 查看的人在这个战队里面
            apply_team_status = 1  ## 有战队的不显示按钮
            if u_team_d.get('team_position')==2: 
                apply_team_status = 2  ## 队长可生成贴吧招募贴
        team_data = TM.GetTeamDBYID(team_id)
        for team in team_data:
            team['team_icon'] = app_setting.QINIUHOST + team.get('team_icon')
            team_rank_d = TM.select('team_rank',dict(team_id = team_id))
            team['team_type'] = getTeamType().get(team.get('team_type',1))
            recruit = team.pop('recruit','\x00')
            if apply_team_status ==2:
                team['recruit'] = 0 if recruit=='\x00' else 1
            team['rank'] = team_rank_d.get('rank','未知')
            team['competition_point'] = team_rank_d.get('competition_point',0)
            team['team_position'] = apply_team_status
            team.pop('team_leader_id',None)
        ## 查看是否已关注该战队
        focus_on = 0
        if TM.select("focus_on",dict(user_id  = user_id, team_id = team_id)):
            focus_on = 1
        return dict(code =0,datas = team_data, focus_on = focus_on)


# 获取战队成员
class  TeamMember(Resource):

    ###
    def get(self):
        query = request.values
        token = query.get('token')
        team_id = query.get('team_id')
        nickname = query.get('nickname')
        check_user_id = query.get('user_id')
        user_id = 0
        try:
            team_id = int(team_id)
        except Exception as e:
            return dict(code = 1,msg= '非法操作')
        if token and  tken.verify_auth_token(token):
            user_id = tken.verify_auth_token(token).get('id')
        team_data = TM.select('game_team',dict(id =team_id),field= ['team_leader_id, recruit'])
        if not team_data:
            return dict(code = 1 ,msg = '战队不存在')
        recruit = 1 if team_data.get("recruit")=='\x01' else 0
        isin_team = 0
        if check_user_id:
            check_user_id = int(check_user_id)
            _team_d = TM.select("user_team", dict(user_id = check_user_id), field = [' team_id '])
            if _team_d and _team_d.get('team_id')!=team_id:
                isin_team = 1
        filter_params = dict(team_id = team_id)
        if nickname:
            filter_params['nickname'] = nickname
        team_user_d = TM.team_user(filter_params)
        ## 查找用户是否在战队里面
        position_status =  -1
        if user_id:
            for team_user in team_user_d:
                team_user['icon'] = team_user.get('icon')
                team_position = team_user.get('team_position',0)
                team_user['team_position'] = team_position
                if team_user.get('user_id')==int(user_id):
                    position_status = team_position

        return dict(code= 0 ,datas = team_user_d,position_status = position_status,
         isin_team = isin_team, recruit = recruit)

    def post(self):
        pass

    def put(self):
        ## 解散战队或者退出战队
        query = request.json
        token = query.get('token')
        if not token or not tken.verify_auth_token(token):
            return dict(code = 1, msg = '请登陆')
        user_id = tken.verify_auth_token(token).get('id')
        team_id = query.get('team_id')
        try:
            team_id = int(team_id)
            status = int(query.get('status',0))
        except Exception as e:
            return dict(code = 1,msg= '非法操作')


        
        if status not in [1,2]:
            return dict(code=22, msg = '参数错误')

        team_data = TM.select('game_team',dict(id = team_id,dissolve =0))
        if not team_data:
            return dict(code = 1, msg= '战队不存在')
        # dissolve = query.get('dissolve',0)
        # if not dissolve:
        #     return dict(code= 1, msg = '战队已解散')
        msg = ''
        sql_list = []
        if status ==1 and  int(user_id) == int(team_data.get('team_leader_id')):
            ## 这是解散战队
            ## 手机验证吗验证
            code = query.get("code")
            check_code_d = TM.select('sms_record', dict(code = code))
            mobile = query.get("mobile")
            if str(mobile)!= check_code_d.get('phone') or int(code)!=int(check_code_d.get('code')) or check_code_d.get("type")!=2:
                return dict(code = 30009, msg = '验证码错误')

            if check_code_d.get('status')!=0:
                return dict(code= 30009, msg = '验证码无效')

            if (datetime.datetime.now() - check_code_d.get("create_time")).seconds >5*60:
                TM.update('sms_record',dict(status = 2), dict(id = check_code_d.get("id")))
                return dict(code = 30009, msg = '验证码过期')
            ##
            sql_list.append(TM.delete_sql('game_team', dict(id = team_id)))
            sql_list.append(TM.delete_sql('user_team',dict(team_id = team_id)))
            ret = TM.trance(sql_list)
            if ret:
                msg = '成功解散'
                TM.update('sms_record',dict(status = 1), dict(id =check_code_d.get("id")))
            else:
                msg = '解散失败'
        else:
            ## 队员退出战队

            ## 查找队员是否在战队里面
            user_in_team = TM.select('user_team',dict(user_id = user_id, team_id = team_id))
            msg = '已退出战队'
            if user_in_team:
                ## 如果存在更新战队信息，退出战队
                now_has_number = team_data.get('has_member') -1
                sql_list.append(TM.delete_sql('user_team',dict(user_id = user_id, team_id = team_id)))
                sql_list.append(TM.update_sql('game_team',dict(has_member = now_has_number),dict(id = team_id)))
                ret = TM.trance(sql_list)
                if ret:
                    msg = '已退出战队'
                else:
                    msg = '退出失败'
        return dict(code= 0,msg = msg)

## 战队成员身份

class TeamPosition(Resource):

    def get(self):
        pass


    def post(self):

        query = request.json

    def put(self):
        ## 战队踢人或者任命
        query = request.json
        token = query.get('token')
        if not token or not tken.verify_auth_token(token):
            return dict(code = 0 ,msg ='请登陆')
        team_id = query.get('team_id')
        user_id = query.get('user_id',0)
        team_position = query.get('team_position',0)
        try:
            user_id = int(user_id)
            team_id = int(team_id)
        except Exception as e:
            return dict(code = 1, msg= '法非操作')
        team_leader_id = tken.verify_auth_token(token).get('id')
        please_leave = query.get('please_leave',0)

        us_team_s = TM.select('user_team', dict(user_id = team_leader_id), field = [' id ,team_position '])
        if not us_team_s and us_team_s.get('team_position')==0:
            return dict(code = 1 ,msg = '没有操作权限')

        team_data  = TM.select('game_team',dict(id = team_id))
        if not team_data:
            return dict(code = 1, msg = '战队不存在')
        if please_leave:
            ## 请离人员
            sql_list = []
            now_has_number = team_data.get('has_member',0) -1
            sql_list.append(TM.delete_sql('user_team',dict(user_id = user_id, team_id = team_id)))
            sql_list.append(TM.update_sql('game_team',dict(has_member = now_has_number),dict(id = team_id)))
            ret = TM.trance(sql_list)
            if ret:
                return dict(code = 0,msg = '已请离战队')
            else:
                return dict(code = 0, msg = '请离战队成员失败')
        if us_team_s.get('team_position')!=2:
            return dict(code=1, msg = '您不是队长')
        if team_position not in [0,1]:
            return dict(code = 0, msg = '操作不合法')
        if team_position==1:
            if len(TM.select_all('user_team',dict(team_id = team_id, team_position = 1)))>=2:
                return dict(code = 0 ,msg = '命副队人数已上限')

        ret = TM.update('user_team',dict(team_position = team_position),dict(team_id= team_id,user_id = user_id))
        if ret:
            return dict(code= 0, msg= '任命成功')
        return dict(code= 0, msg = '没有发生变化')

## 赛事管理
class EventManageMent(Resource):

    def get(self):
        status_list = ['等待开赛','已报名']
        query = request.values
        team_id = query.get('team_id')
        offset = query.get('offset',0)
        limit = query.get('limit',10)
        try:
            team_id = int(team_id)
            offset = int(offset)
            limit = int(limit)
        except Exception as e:
            return dict(code = 1, msg= '非法操作')

        token = query.get('token')
        op_user_id = 0
        if token and tken.verify_auth_token(token):
            op_user_id = tken.verify_auth_token(token).get('id')
        game_team_d = TM.select('game_team',dict(id = team_id, dissolve =0))
        if not game_team_d:
            return dict(code= 1, msg = '战队不存在')
        op_team = 0 ## 1时为队长权限可更换战队参赛成员
        if int(op_user_id)==int(game_team_d.get('team_leader_id')):
            op_team = 1
        ## 获取战队赛事信息
        team_event_d,count = TM.GetTeamEventData(team_id, offset, limit)
        if team_event_d:
            game_names = GetGameData()
            game_icons =  GetGameData(icon= True)
        datas = []
        for team_event in team_event_d:

            flag =  deal_time_for_event_s(team_event.get('apply_start_time'),team_event.get('apply_end_time'),
                team_event.get('game_start_time'),team_event.get('game_end_time'))
            if flag=='报名中':
                flag = '已报名'
            if op_team==1 and flag in status_list:
                op_team = 1
            else:
                op_team  =0
            if team_event.get("apply_end_time")<=datetime.datetime.now():
                op_team = 0
            game_id = team_event.get('game_id')
            game_name = game_names.get(game_id)
            game_icon = app_setting.QINIUHOST+ game_icons.get(game_id)
            has_teams = team_event.get('has_teams')
            max_teams  = team_event.get('max_teams')
            e_t_name  = GetEventType().get(team_event.get('event_type_id'))
            # team_event['team_icon'] = app_setting.QINIUHOST + team_event.get('team_icon')
            ## 获取参赛成员
            join_member = TM.aoth_event_user(team_event.get('auto_id'))
            user_data= []
            auto_event_id = 0
            for join in join_member:
                user_data.append(dict(
                            id = join.get('id'),
                            icon =app_setting.QINIUHOST+ join.get('icon'),
                            au_id = join.get('auth_event_to_user_id')
                    ))
                if auto_event_id ==0:
                    auto_event_id = join.get('auto_event_id')
            datas.append( dict(
                        flag = flag,
                        events_title = team_event.get('events_title'),
                        game_name= game_name,
                        game_icon= game_icon,
                        total_bonus = team_event.get('total_bonus',0),
                        has_max_team = str(has_teams)+'/'+str(max_teams),
                        award_type = team_event.get('award_type'),
                        award_name =team_event.get('award_name'),
                        op_team = op_team,
                        user_data = user_data,
                        e_t_name = e_t_name,
                        auto_event_id = auto_event_id
                ))
        return dict(code= 0, datas = datas,total = count,op_team = op_team)
        # return dict(code= 0, datas = datas ,op_user_id = op_user_id,op_team = op_team)

    def  post(self):
        pass
        # img_src = 'http://wx2.sinaimg.cn/mw690/ac38503ely1fesz8m0ov6j20qo140dix.jpg'
        # # print request.files.get('file').read()
        # import requests as req
        # from PIL import Image
        # from io import BytesIO
        # response = req.get(img_src)
        # image = Image.open(BytesIO(response.content))
        # print image.size
        # return dict(code= 1)
    ## 参赛成员替换
    def put(self):
        status_list = ['报名中','等待开赛']
        query = request.json
        token = query.get('token')
        user_id = query.get('user_id')
        event_id = query.get('event_id')
        au_id = query.get('au_id')
        team_id = query.get('team_id')
        try:
            user_id  = int(user_id)
            event_id = int(event_id)
            au_id = int(au_id)
            team_id  = int(team_id)
        except Exception as e:
            return dict(code= 0, msg = '参数错误')
        _tken = tken.verify_auth_token(token)
        if not token or not _tken:
            return dict(code = 0, msg = '请登陆')

        ## 查找替换者是否再这个战队

        user_td = TM.select('user_team',dict(team_id = team_id,user_id = user_id))
        if not user_td:
            return dict(code=0,msg = '成员不在战队中')
        event_d = TM.select('hot_event',dict(id = event_id))
        if not event_d:
            ## 生成日志
            return dict(code= 0, msg= '非法操作')

        ## 判断赛事目前是否可以替换成员
        status_flag = deal_time_for_event_s(event_d.get('apply_start_time'), 
            event_d.get('apply_end_time'),event_d.get('game_start_time'),event_d.get('game_end_time'))

        if status_flag not in status_list:
            return dict(code = 0, msg = '当前赛事已不可以替换成员')

        team_d = TM.select('user_team', dict(team_id = team_id, user_id = _tken.get('id')))
        if not team_d or team_d.get('team_position',0)==0:
            return dict(code = 0, msg ='权限不足')


        ret  = TM.update('auth_event_to_user',dict(user_id  = user_id), dict(id = au_id))
        return dict(code=0,msg = '替换成功')









## 点赞
class GiveALike(Resource):

    def post(self):

        query = request.json
        token = query.get('token')
        user_id = query.get('user_id')
        if not int(user_id) or not token or not tken.verify_auth_token(token) or int(user_id)!=int(tken.verify_auth_token(token).get('id')):
            return dict(code = 0, msg = '请登陆')
        team_id = query.get('team_id')
        try:
            team_id = int(team_id)
        except Exception as e:
            return dict(code = 0,msg = '非法操作')
        user_id = tken.verify_auth_token(token).get('id')
        _type = query.get('like_type',0) # 0取消点赞1点赞
        team_d = TM.select('game_team',dict(id = team_id))
        like_num  = team_d.get('like_num',0)
        #3 获取点赞信息
        check_cond=  dict(user_id = user_id, team_id = team_id)
        sql_list=[]
        if _type==0:
            u_like_data =  TM.select('give_a_like',check_cond) 
            if u_like_data:
                ## 存在取消点赞
                like_num = like_num-1 if like_num else 0
                sql_list.append(TM.update_sql('game_team',dict(like_num = like_num),dict(id = team_id)))
                sql_list.append(TM.delete_sql('give_a_like',dict(id= u_like_data.get('id'))))
                ret = TM.trance(sql_list) 
                if ret:
                    return dict(code= 0, msg='成功取消点赞')
                else:
                    return dict(code= 0, msg = '取消失败')
        elif _type==1:
            u_like_data =  TM.select('give_a_like',check_cond) 
            if u_like_data:
                return dict(code= 0,msg = '已点赞')
            sql_list.append(TM.update_sql('game_team',dict(like_num = like_num+1),dict(id = team_id)))
            check_cond['create_time'] = datetime.datetime.now()
            sql_list.append(TM.insert_sql('give_a_like',check_cond))
            ret = TM.trance(sql_list)
            if ret:
                return dict(code=0, msg ='点赞成功')

            return dict(code= 0, msg = '系统出错')

        return dict(code= 0, msg = '非法操作')

## 关注
class FocusOn(Resource):
    ## 获取用户个人关注
    def get(self):
        query = request.values
        token = query.get('token')
        user_id = query.get('user_id')
        if not user_id or not token or not tken.verify_auth_token(token) \
        or int(user_id)!=int(tken.verify_auth_token(token).get('id')):
            return dict(code = 1, msg ='请登陆')
        offset = query.get('offset',0)
        limit = query.get('limit',10)
        try:
            offset  = int(offset)
            limit = int(limit)
        except Exception as e:
            return dict(code = 1, msg = '参数错误')
        user_id  = tken.verify_auth_token(token).get('id')
        focus_d, count = TM.UserFocus(dict(user_id = user_id,offset = offset, limit = limit),count=  True)
        return dict(code = 0, datas = focus_d, total = count[0].get('count'))


    def post(self):

        query = request.json
        token = query.get('token')
        user_id = query.get('user_id')
        if not user_id or not token or not tken.verify_auth_token(token) \
        or int(user_id)!=int(tken.verify_auth_token(token).get('id')):
            return dict(code = 0, msg ='请登陆')
        team_id = query.get('team_id')
        try:
            team_id = int(team_id)
        except Exception as e:
            return dict(code = 0,msg = '非法操作')
        user_id = tken.verify_auth_token(token).get('id')
        _type = query.get('focus_type',0) # 0取消关注1关注
        team_d = TM.select('game_team',dict(id = team_id))
        focus_on  = team_d.get('focus_on',0)

        check_cond=  dict(user_id = user_id, team_id = team_id)
        sql_list=[]

        if _type ==0:
            focus_data = TM.select('focus_on',check_cond)
            if focus_data:
                focus_on = focus_on - 1 if focus_on else 0
                sql_list.append(TM.update_sql('game_team',dict(focus_on = focus_on),dict(id = team_id)))
                sql_list.append(TM.delete_sql('focus_on',dict(id = focus_data.get('id'))))
                ret = TM.trance(sql_list)
                if ret:
                    return dict(code = 0, msg = '已取消关注')
            return dict(code=0, msg = '还未关注')
        elif _type ==1:
            focus_data = TM.select('focus_on',check_cond)
            if focus_data:
                return dict(code = 0, msg  ='已关注')
            sql_list.append(TM.update_sql('game_team',dict(focus_on = focus_on +1),dict(id = team_id)))
            check_cond['create_time'] = datetime.datetime.now()
            sql_list.append(TM.insert_sql('focus_on',check_cond))
            ret = TM.trance(sql_list)
            if ret:
                return dict(code = 0 ,msg = '成功关注')
            return dict(code= 0 ,msg  = '关注失败')
        return dict(code = 0 ,msg = '操作失败')

## 参赛队员管理
## 获取可替换的队员
class UpdateTeamOfEventInfo(Resource):
    ## 某场比赛替换队员
    def get(self):
        query = request.values
        token  = query.get('token')
        user_id  = query.get('user_id')
        if not user_id or not token or not tken.verify_auth_token(token) or int(user_id)!=tken.verify_auth_token(token):
            return dict(code= 1,msg = '请登陆')
        team_id = query.get('team_id')
        event_id = query.get('event_id')
        try:
            team_id  = int(team_id)
            event_id = int(event_id)
        except Exception as e:
            return dict(code=1, msg = '非法操作')

        op_user_id  = tken.verify_auth_token(token).get('id')
        ## 查看操作者是否有权限
        game_team_d = TM.select('game_team',dict(id = team_id))
        if not game_team_d:
            return dict(code = 30006, msg = '战队不存在')
        if game_team_d.get('team_leader_id')!=int(op_user_id):
            return dict(code= 30007, msg = '您不是队长')

        ## 获取战队成员

        team_member = TM.team_user(dict(team_id = team_id))
        ## 获取参赛战队成员
        join_event_d = TM.JoinEventUser(dict(team_id = team_id, event_id = event_id))
        team_user_id = [ join_.get('user_id') for join_ in join_event_d]
        return dict(code= 0, datas = [ team_ for team_ in team_member if team_.get('user_id') not in team_user_id])


    def post(self):
        pass


    ## 取消赛事报名
    def put(self):
        query = request.json
        token  = query.get('token')
        team_id = query.get('team_id')
        event_id = query.get('event_id')
        try:
            team_id = int(team_id)
            event_id = int(event_id)
        except Exception as e:
            return dict(code = 0, msg = '操作有误')
        if not token or not tken.verify_auth_token(token):
            return dict(code = 0, msg = '请登陆')
        op_user_id = int(tken.verify_auth_token(token).get('id'))
        team_d = TM.select('game_team',dict(id = team_id))
        if not team_d or team_d.get('team_leader_id')!=op_user_id:
            return dict(code = 0 , msg = '没有操作权限')
        team_event_d = TM.select('auth_event',dict(team_id = team_id, event_id = event_id,status = 0),field = ['id'])
        if not team_event_d:
            return dict(code = 0, msg= '')
        sql_list = []
        _id = team_event_d.get('id')
        sql_list.append(TM.update_sql('auth_event',dict(status = 1),dict(id= _id)))
        sql_list.append(TM.delete_sql('auth_event_to_user',dict(auto_event_id = _id)))
        ret = TM.trance(sql_list)
        if not ret:
            return dict(code = 0 ,msg = '取消失败,稍后尝试')
        return dict(code= 0, msg  = '取消报名')



## 荣誉
class honor(Resource):

    def get(self):
        query = request.values

        token = query.get('token')
        team_id = query.get('team_id')
        offset = query.get('offset',0)
        limit = query.get('limit',10)
        try:
            offset = int(offset)
            limit = int(limit)
            team_id = int(team_id)
        except Exception as e:
            return dict(code = 1, msg = '非法操作')

        ## 查看战队是否存在
        team_d = TM.select('game_team',dict(id=  team_id, dissolve = 0))
        if not team_d:
            return dict(code= 1, msg = '战队不存在')

        teamhonor_d,count = TM.teamhonor(dict(team_id  = team_id), offset, limit)
        game_names = GetGameData()
        game_icons = GetGameData(True)
        datas = []
        for team in teamhonor_d:
            game_id = team.get('game_id')
            bonus_type = team.get('bonus_type')
            bonus =team.get('bonus',0)
            award_name = team.get('award_name','')
            if bonus_type==0 and not bonus:
                award = str(bonus) + ' 彩豆'
            elif bonus_type ==1 and bonus:
                award = str(bonus) + ' 元'
            else:
                award = award_name
            datas.append(dict(
                    events_title = team.get('events_title'),
                    rank = team.get('rank'),
                    game_name = game_names.get(game_id),
                    game_icon = app_setting.QINIUHOST+game_icons.get(game_id) ,
                    event_level_name = GetEventType().get(team.get('event_type_id')),
                    award = award,
                    create_time = team.get('create_time').strftime('%Y-%m-%d')


                ))

        return dict(code= 0, datas = datas,total = count)

## 用户的个人游戏信息
## 未清楚如何对接游戏绑定
class UserGame(Resource):

    def get(self):
        query = request.values
        token = query.get('token','')
        user_id = query.get('user_id',0)
        if not user_id or  not token or not tken.verify_auth_token(token) or int(user_id)!=int(tken.verify_auth_token(token).get('id')):
            return dict(code = 30005, msg = '请登陆')
        offset = query.get('offset',0)
        limit = query.get('limit',10)

        user_id  = tken.verify_auth_token(token).get('id')
        user_game_d = TM.select_all('my_game',dict(user_id = user_id),field = ['game_id , guser_name, dan , id , precinct, choosesuit'],
            offset = int(offset), limit = int(limit), order_by='  order by id desc ')
        count_d = TM.select_all('my_game',dict(user_id = user_id),field = [' count(1)count'])

        game_names = GetGameData()
        game_icons = GetGameData(True)
        for user_game in user_game_d:
            game_id = user_game.pop('game_id',None)
            user_game['game_name'] = game_names.get(game_id, str(game_id))
            user_game['icon']  = game_icons.get(game_id,str(game_id))
        return dict(code = 0, datas  = user_game_d,total = count_d[0].get('count'))
    ##添加个人游戏
    def post(self):
        query = request.json 
        game_id   = query.get('game_id')
        token = query.get('token')
        platform  = query.get('platform',0)
        user_id  = query.get("user_id",0)
        precinct = query.get('precinct','')
        choosesuit = query.get('choosesuit','')
        if not user_id or  not token or not tken.verify_auth_token(token) or int(user_id)!=int(tken.verify_auth_token(token).get("id")):
            return dict(code  = 30005, msg = '请登陆')
        game_data = TM.select('game', dict(id = game_id, delete_flag = '\x01'))
        if not game_data:
            return dict(code = 30006 ,msg  = '非法操作')

        user_id = tken.verify_auth_token(token).get('id')
        check_u_game_d = TM.select('my_game',dict(user_id = user_id , game_id = game_id))
        if check_u_game_d:
            return dict(code= 30007 ,msg = '已存在该游戏，请前往修改绑定')
        ## 从游戏公司获取用户的游戏账号信息,例如游戏id，游戏段位
        u_game_id = query.get('u_game_id',randomStr(10))
        dan = query.get('dan','最强王者 %s星' % random.randint(0,100))
        last_id = TM.add('my_game', dict(user_id = user_id, game_id = game_id,
            guser_name = u_game_id,platform = platform, dan = dan, create_time = datetime.datetime.now(),
            precinct = precinct, choosesuit = choosesuit))
        if last_id:
            return dict(code = 0 ,msg = '添加成功')
        return dict(code= 30008 ,msg = '添加失败')

    ## 修改个人游戏
    def put(self):
        query = request.json
        token = query.get('token')

        platform  = query.get('platform',0)
        user_id  = query.get("user_id",0)
        precinct = query.get('precinct','')
        choosesuit = query.get('choosesuit','')
        if not user_id or  not token or not tken.verify_auth_token(token) or int(user_id)!=int(tken.verify_auth_token(token).get("id")):
            return dict(code = 30005, msg = '请登陆')
        _id = query.get('ugame_id')   
        game_account = query.get('game_account','')
        game_pwd = query.get('game_pwd')
        try:
            _id = int(_id)
        except Exception as e:
            return dict(code= 30006 ,msg = '非法操作')

        u_game_id  = query.get('u_game_id',randomStr(10))
        dan = query.get('dan','最强王者 %s星' % random.randint(0,100))
        platform = query.get('platform',0)
        update_d =dict(guser_name = u_game_id , dan = dan , platform = platform)
        if precinct:
            update_d['precinct'] = precinct
        if choosesuit:
            update_d['choosesuit'] = choosesuit
        ret  = TM.update('my_game',update_d,dict(id = _id))

        if ret:
            return dict(code = 0, msg = '修改成功')
        return dict(code= 0 ,msg  = '修改失败')




    ## 删除个人游戏
    def delete(self):

        query = request.json
        token = query.get('token')
        user_id = query.get('user_id')
        if not user_id or  not token or not tken.verify_auth_token(token) or int(user_id)!=int(tken.verify_auth_token(token).get("id")):
            return dict(code = 30005, msg = '请登陆')

        _id = query.get('ugame_id')
        print _id
        check_d  = TM.select("my_game",dict(id =_id))
        print check_d
        if not check_d or int(user_id)!=int(check_d.get("user_id")):
            return dict(code = 30006, msg = '非法操作')
        ret  = TM.delete('my_game',dict(id = _id))
        if ret:
            return dict(code = 0, msg = '删除成功')
        return dict(code = 0, msg = '删除失败')



## 战队审核
class CheckTeamMember(Resource):
    ## 根据战队队长或者副队长的审核权限来显示是否有需要审核的人员
    def get(self):
        query = request.values
        token = query.get('token')
        user_id = query.get('user_id')
        if not token or not tken.verify_auth_token(token) or not user_id or int(user_id)!=int(tken.verify_auth_token(token).get('id')):
            return dict(code = 1 ,msg = '请登陆')

        user_id  = tken.verify_auth_token(token).get('id')
        offset = query.get('offset',0)
        limit  = query.get('limit',10)
        user_team_d = TM.select('user_team',dict(user_id = user_id))
        if not user_team_d or user_team_d.get('team_position',0)==0:
            return dict(code = 40008, msg = '没有审核权限')

        apply_team_d,count = TM.check_u_team(dict(team_id = user_team_d.get('team_id'), status = 0 ),offset  = offset , limit = limit)
        for apply_ in apply_team_d:
            apply_['icon'] = app_setting.QINIUHOST + apply_.get('icon')
        return dict(code = 0, datas = apply_team_d,total = count)



    def post(self):
        pass

    def put(self):
        query  = request.json
        token = query.get('token')
        status = query.get('status',0)
        user_id = query.get('user_id',0)
        if not user_id or  not token or not tken.verify_auth_token(token) or int(user_id)!=int(tken.verify_auth_token(token).get('id')):
            return dict(code = 1, msg = '请登陆')

        _id = query.get('id',0)
        try:
            _id = int(_id)
            status  = int(status)
        except Exception as e:
            return dict(code = 1, msg = '参数错误')
        apply_u_data  = TM.select('apply_team',dict(id = _id,status = 0))
        if not apply_u_data:
            return dict(code = 0, msg = '已处理')

        user_id  = tken.verify_auth_token(token).get('id')
        user_team_d = TM.select('user_team',dict(user_id = user_id))

        if not user_team_d or user_team_d.get('team_position',0)==0:
            return dict(code = 30006, msg = '没有审核权限')      
        apply_u_id  = apply_u_data.get('user_id')
        team_id = user_team_d.get('team_id')
        team_data = TM.select('game_team',dict(id = team_id))
        sql_list = []
        if status ==2:
            message = u'你申请的战队  '  + team_data.get('team_name','') + u'  拒绝加入，可到其他战队看看哦~'
            sql_list.append(TM.update_sql('apply_team', dict(status = 2), dict(id = _id)))
            sql_list.append(TM.insert_sql('user_message', dict(user_id = apply_u_id, message = message, create_time = datetime.datetime.now())))
            ret  = TM.trance(sql_list)
            if ret:
                ### 添加申请者的消息
                return dict(code = 0,msg = '操作成功')
        if int(team_data.get('has_member')) >= int(team_data.get('max_member')):
            return  dict(code = 1, msg = '战队满人')
        if status ==1:
            message = u'加入战队  ' + team_data.get('team_name','') + u'  有了战队要好好加油~'
            sql_list.append(TM.update_sql('game_team', dict(has_member = team_data.get('has_member') + 1),dict(id = team_data.get('id'))))
            sql_list.append(TM.update_sql('apply_team',dict(status = 1),dict(id = _id)))
            sql_list.append(TM.insert_sql('user_message', dict(user_id  = apply_u_id, message = message,create_time = datetime.datetime.now())))
            sql_list.append(TM.insert_sql('user_team',dict(user_id = apply_u_id, team_id = team_id, create_time = datetime.datetime.now())))
            ret = TM.trance(sql_list)
            if ret:
                return dict(code = 0 ,msg = '操作成功')

        return dict(code  = 1, msg = '操作失败')



    def delete(self):
        pass

## 用户的消息
class UserMesage(Resource):
    ## 获取用户个人的消息
    def get(self):
        query = request.values
        token = query.get('token')
        user_id = query.get('user_id')
        if not user_id or not token or not tken.verify_auth_token(token) or int(user_id)!=int(tken.verify_auth_token(token).get('id')):
            return dict(code = 1, msg= '请登陆')

        offset = query.get('offset',0)
        limit = query.get('limit',10)
        try:
            offset = int(offset)
            limit = int(limit)
        except Exception as e:
            return dict(code = 1, msg= '参数格式错误')
        user_id  = tken.verify_auth_token(token).get('id')
        user_message_d = TM.select_all('user_message',dict(user_id = user_id),field = [' message,  create_time'],
            offset = offset, limit = limit, order_by = ' order by create_time desc ')
        count_d  = TM.select_all('user_message',dict(user_id  = user_id), field = ['  count(1)count '])

        for user_m in user_message_d:
            user_m['create_time'] = user_m.get('create_time').strftime('%Y-%m-%d %H:%M:%S')

        return dict(code = 0, datas = user_message_d,total = count_d[0].get('count'))

## 用户个人赛事

class UserTournament(Resource):

    def get(self):
        try:
            query = request.values
            token = query.get('token')

            if not token or not tken.verify_auth_token(token):
                return dict(code = 1, msg= '请登陆')
            offset = query.get('offset',0)
            limit = query.get('limit',10)
            try:
                offset = int(offset)
                limit = int(limit)
            except Exception as e:
                return dict(code = 1, msg= '参数格式错误')
            user_id = tken.verify_auth_token(token).get('id')
            ## 查看用户是否有战队

            user_team  = TM.select('user_team', dict(user_id = user_id))
            if not user_team:
                return dict(code= 1, msg= '您还没有加入战队')

            datas = []
            event_d,count = TM.UserEvent(dict( user_id = user_id , offset = offset , limit = limit))
            for event in event_d:
                apply_start_time = event.get('apply_start_time')
                apply_end_time = event.get('apply_end_time')
                game_start_time = event.get('game_start_time')
                game_end_time = event.get('game_end_time')
                status = deal_time_for_event_s(apply_start_time, apply_end_time,game_start_time, game_end_time)
                datas.append(dict(
                            event_title  = event.get('events_title'),
                            id = event.get('id'),
                            status = status

                    ))
            return dict(code = 0, datas = datas, total = count)
        except Exception as e:
            return dict(code = 30005, msg = '哎哟，出错了!')


## 用户信息管理
class UserMessgeManage(Resource):

    ## 
    def get(self):
        query = request.values
        token  = query.get('token')
        # if not token or not tken.verify_auth_token(token):
        #     return dict(code=0 ,msg = '请登陆')
        user_id = query.get('user_id')
        if not user_id or not token or not tken.verify_auth_token(token) or int(user_id)!=int(tken.verify_auth_token(token).get('id')):
            return dict(code = 1 ,msg = '非法操作')
        ## 
        op_status = 0
        if token and tken.verify_auth_token(token) and tken.verify_auth_token(token).get('id')==user_id:
            op_status = 1
        user_d = TM.select('users',dict(id = user_id, status= 0), field = [' phone, addr, icon, nickname,gender '])
        if not user_d:
            return dict(code = 30005, msg = '用户不存在')
        user_d['icon'] = app_setting.QINIUHOST + user_d.get('icon')
        yz_log.info(user_d)
        user_d['gender'] = 0 if user_d.get('gender')==b'\x00' else 1
        auth_d = TM.select_all('user_auths',dict(user_id = user_id, status = 0),field = [' identity_type, nickname , identifier'])

        user_d['platform_login_l'] = []
        user_d.get('platform_login_l').append({'addr': user_d.get('addr')})
        for auth in auth_d:
            if auth.get('identity_type') :
                if auth.get("identity_type")=='phone':
                    nickname  = auth.get('identifier')
                else:
                    nickname  =auth.get('nickname')
                user_d.get('platform_login_l').append({auth.get('identity_type'): nickname,"type":auth.get('identity_type')})
        yz_log.info(user_d)
        u_t_d = TM.GetTeamByUserId(dict(user_id = user_id))
        user_d['team_name'] = ''
        team_icon = ''
        if u_t_d:
            user_d['team_name'] = u_t_d[0].get('team_name')
            user_d['team_id'] = u_t_d[0].get('id')
            if u_t_d[0].get('team_icon'):
                team_icon = app_setting.QINIUHOST + u_t_d[0].get('team_icon')
        user_d['team_icon'] = team_icon
        user_d['honor'] = []
        user_d.pop('team_id',None)
        if user_d.get('team_name'):
            team_d = TM.user_team_m(dict(user_id = user_id, offset = 0, limit =10))
            if team_d:
                for d in team_d:
                    rank = str(d.get('rank'))
                    if rank =='1':
                        rank = u' 冠军'
                    elif rank == '2':
                        rank = u' 亚军'
                    elif rank =='3':
                        rank = u' 季军'
                    user_d['honor'].append(dict(events_title = d.get('events_title','') ,
                                                rank = rank,
                                                create_time = d.get('create_time').strftime('%Y-%m-%d'),
                                                game_name = GetGameData().get(d.get('game_id'))
                                                ))

        ## 贴吧信息

        return dict(code= 0, datas = [user_d], op_status = op_status)


    def post(self):
        pass

    ## 修改个人信息
    def put(self):
        query = request.json

        user_id = query.get('user_id')
        if not user_id:
            return  dict(code= 0, msg = '请登陆')
        token = query.get('token')
        if not token or not tken.verify_auth_token(token):
            return dict(code=1, msg = '请登陆') 
        
        if int(user_id) !=int(tken.verify_auth_token(token).get('id')):
            return dict(code=0,msg = '操作不合法')
        user_id = int(tken.verify_auth_token(token).get('id'))
        phone = query.get('phone')
        addr = query.get('addr')

        sql_list = []
        if phone:
            status = checkphone(phone)
            if status is False:
                return dict(code= 1, msg = '手机格式错误')
            update_d = dict(phone = phone)
            if addr:
                update_d['addr'] = addr
            sql_list.append(TM.update_sql('users',update_d, dict(id = user_id)))
            check_u = dict(user_id = user_id, identity_type = 'phone')
            if TM.select('user_auths',check_u):
                sql_list.append(TM.update_sql('user_auths',dict(identifier = phone),check_u))
            else:
                check_u['identifier'] = phone
                sql_list.append(TM.insert_sql('user_auths', check_u))
        if not sql_list and addr:
            sql_list.append(TM.update_sql('users'),dict(addr = addr), dict(id = user_id))
        ret = TM.trance(sql_list)
        if ret:
            return dict(code = 0, msg = '修改成功')
        return dict(code= 1, msg = '修改失败')

    def delete(self):
        pass

class UserHonor(Resource):

    def get(self):

        ## 获取个人荣誉信息
        query  = request.values
        offset = int(query.get('offset',0))
        limit = int(query.get('limit',10))
        user_id = int(query.get('user_id',0))
        token = query.get('token')
        if not user_id or not token or not tken.verify_auth_token(token) or user_id!=int(tken.verify_auth_token(token).get('id')):
            return dict(code=1, msg = '请登陆')

        UH_datas = TM.GetHonorById(dict(user_id = user_id, team_id = team_id),offset, limit)





##战队赛事替换手机端
class TeamModifyMember(Resource):

    def get(self):
        query = request.values
        token = query.get('token')
        user_id = query.get('user_id',0)
        team_id = query.get('team_id',0)
        auto_event_id = query.get('auto_event_id')
        try:
            user_id = int(user_id)
            team_id = int(team_id)
            auto_event_id = int(auto_event_id)
        except Exception as e:
            return dict(code= 30006,msg = '参数格式错误')

        if not user_id or not token or not tken.verify_auth_token(token) or user_id!=int(tken.verify_auth_token(token).get('id')):
            return dict(code = 3,msg = '请登陆')

        ## 查看战队报名信息是否存在
        team_event_d = TM.select('auth_event',dict(id =auto_event_id , status = 0), field = [' event_id '])
        if not team_event_d:
            return dict(code  = 30007, msg = '战队未报名该赛事')

        event_d = TM.select('hot_event', dict(id = team_event_d.get('event_id')), field = [' team_num '])
        ## 查看主动修改者是否有权限修改
        # modify_permission = TM.select('user_team',dict(user_id = user_id, team_id = team_id , team_position =2))
        # if not modify_permission:
        #     return dict(code= 30008, msg = '权限不足')
        ## 根据auto_event_id 查找已经报名了用户id
        auth_event_to_user = TM.select_all('auth_event_to_user',dict(auto_event_id = auto_event_id),
            field = [' user_id '])
        if not auth_event_to_user:
            return dict(code= 30009, msg = '系统出错')
        user_id_list = []
        for u in auth_event_to_user:
            user_id_list.append(u.get('user_id'))

        ## 查找战队所有的成员，有了游戏之后根据成员是否有这样的游戏来筛选
        team_u_d = TM.GetUserToEvent(team_id)
        for team in team_u_d:
            team['icon']  = app_setting.QINIUHOST + team.get('icon')
            is_join = 0
            if team.get('id') in user_id_list:
                is_join = 1
            team['is_join']  = is_join


        return dict(code = 0, datas = team_u_d, team_num = event_d.get('team_num'))

    def put(self):

        query = request.json
        token = query.get('token','')
        user_id = query.get('user_id',0)
        auto_event_id = query.get('auto_event_id',0)
        user_id_list = query.get('u_l',[])

        try:
            user_id  = int(user_id)
            auto_event_id = int(auto_event_id)
        except Exception as e:
            return dict(code = 40009, msg ='参数格式错误')
        if not isinstance(user_id_list,list):
            return dict(code = 40009, msg= '参数类型错误')

        if not user_id or not token or not tken.verify_auth_token(token) or user_id !=int(tken.verify_auth_token(token).get('id')):
            return dict(code=40006, msg = '请登陆')

        ## 查看是否有修改的权限

        u_c_d = TM.select('user_team',dict(user_id = user_id, team_position = 2), field = [' team_id '])
        if not u_c_d:
            return dict(code = 40005, msg = '权限不足')
        #查看报名是否存在
        team_id  = u_c_d.get('team_id')
        sign_e_d = TM.select('auth_event',dict(id = auto_event_id, team_id = team_id))

        if not sign_e_d:
            return dict(code  = 40004, msg  = '非法操作')
        ## 查看赛事是否已结束比赛，如果事则不可以替换队员
        e_d = TM.select('hot_event',dict(id = sign_e_d.get("event_id")), field = [' apply_end_time '])
        if not e_d:
            return dict(code=40005, msg = '赛事不存在')
        if e_d.get("apply_end_time")<=datetime.datetime.now():
            return dict(code = 40004, msg = '赛事已结束报名，不可以再替换')
        u_e_count = TM.select_all('auth_event_to_user', dict(auto_event_id = auto_event_id), field = [' id '])
        sign_member_l = len(u_e_count)
        if sign_member_l!=len(user_id_list):
            return dict(code= 40004, msg = '非法操作')

        ## 开始修改
        sql_list =  []
        # sql_list.append(TM.delete_sql('auth_event_to_user' ,dict(auto_event_id = auto_event_id)))
        for i in range(sign_member_l):
            sql_list.append(TM.update_sql('auth_event_to_user',dict(user_id = user_id_list[i]), dict(id = u_e_count[i].get('id'))))
        ret = TM.trance(sql_list)
        if ret:
            return dict(code = 0, msg = '替换成功')

        return dict(code = 40003, msg = '替换失败')




class AboutMme(Resource):

    def get(self):

        query = request.values
        token = query.get('token')
        user_id  = query.get('user_id',0)
        if not token or not user_id or not tken.verify_auth_token(token) or int(user_id)!=int(tken.verify_auth_token(token).get('id')):
            return dict(code=1, msg  = '请登陆')

        user_id = int(tken.verify_auth_token(token).get('id'))
        my_m_num  = ''
        audit_m_num = ''
        m_num = ''
        ## 获取战队中的职位
        T_position = TM.select('user_team',dict(user_id = user_id), field = [' team_position, team_id '])
        if T_position and T_position.get('team_position',0)!=0:
            apply_t_d = TM.select('apply_team', dict(team_id =T_position.get('team_id'), status = 0), field = [ ' count(1)count '])
            audit_m_num = apply_t_d.get('count')




        return dict(code = 0 ,my_m_num = my_m_num, audit_m_num = audit_m_num,m_num = m_num)

class UserTeam(Resource):
    def get(self):
        try:
            query = request.values

            token = query.get("token")
            user_id = query.get("user_id")

            if not user_id or not token or not tken.verify_auth_token(token) or int(user_id)!=int(tken.verify_auth_token(token).get('id')):
                return dict(code= 40009, msg = '未登陆')
            T_D = TM.select('user_team', dict(user_id = user_id), field =[' team_id '])
            if T_D:
                team_id= T_D.get('team_id')
                team_d =  TM.select("game_team", dict(id = team_id), field = [' team_icon '])
                if team_d:
                    return dict(code = 0, team_id= team_id, team_icon = app_setting.QINIUHOST + team_d.get("team_icon"))
            return dict(code = 30005, msg = 'ss')
        except Exception as e:
            return dict(code = 30006, msg = 'jkj')



class CheckEvent(Resource):

    def get(self):
        ## 根据赛事id来查找相关信息
        try:
            query = request.values

            event_id=  int(query.get('event_id',0))
            event_d = TM.GetEventById(dict(event_id = event_id))

            if not event_d:
                return dict(code= 1 ,msg ='赛事不存在')

            for event in event_d:
                apply_start_time = event.pop('apply_start_time',None)
                apply_end_time = event.pop('apply_end_time',None)
                game_start_time = event.pop('game_start_time',None)
                game_end_time = event.pop('game_end_time',None)
                event['apply_start_time'] = '敬请期待'
                if isinstance(apply_start_time , datetime.datetime):
                    event['apply_start_time'] = apply_start_time.strftime("%Y-%m-%d %M:%H:%S")
                event['status'] = deal_time_for_event_s(apply_start_time, apply_end_time, game_start_time, game_end_time)
                event['event_type']  = event_num(event.get("status"))
                game_icon = ''
                game_id = event.pop('game_id',0)
                if GetGameData(icon = True).get(game_id):
                    game_icon = app_setting.QINIUHOST+GetGameData(icon = True).get(game_id)
                event['game_icon'] = game_icon
                event['gt_name'] = GetEventType().get(event.pop('event_type_id',0))
            award_d = TM.GetAwardByEvntId(event_id)
            return dict(code= 0, datas = event_d , award_d = award_d)
        except Exception as e:
            return dict(code= 30009, msg = str(e))

## 查看别的用户个人信息
class CheckUserMessge(Resource):

    ## 
    def get(self):
        query = request.values
        # if not token or not tken.verify_auth_token(token):
        #     return dict(code=0 ,msg = '请登陆')
        user_id = query.get('user_id')

        user_d = TM.select('users',dict(id = user_id, status= 0), field = [' phone, addr, icon, nickname, gender '])
        if not user_d:
            return dict(code = 30005, msg = '用户不存在')
        user_d['icon'] = app_setting.QINIUHOST + user_d.get('icon')

        u_t_d = TM.GetTeamByUserId(dict(user_id = user_id))
        user_d['team_name'] = ''
        user_d['gender'] = 0 if user_d.get('gender')=='\x00' else 1
        team_icon = ''
        if u_t_d:
            user_d['team_name'] = u_t_d[0].get('team_name')
            user_d['team_id'] = u_t_d[0].get('id')
            if u_t_d[0].get('team_icon'):
                team_icon = app_setting.QINIUHOST + u_t_d[0].get('team_icon')
        user_d['team_icon'] = team_icon
        user_d['honor'] = []
        user_d.pop('team_id',None)
        if user_d.get('team_name'):
            team_d = TM.user_team_m(dict(user_id = user_id, offset = 0, limit =10))
            if team_d:
                for d in team_d:
                    rank = str(d.get('rank'))
                    if rank =='1':
                        rank = u' 冠军'
                    elif rank == '2':
                        rank = u' 亚军'
                    elif rank =='3':
                        rank = u' 季军'
                    user_d['honor'].append(dict(events_title = d.get('events_title','') ,
                                                rank = rank,
                                                create_time = d.get('create_time').strftime('%Y-%m-%d'),
                                                game_name = GetGameData().get(d.get('game_id'))
                                                ))

        ## 贴吧信息

        return dict(code= 0, datas = [user_d])

## 个人荣誉
class PersonalHonor(Resource):

    def get(self):
        query = request.values
        offset = query.get('offset',0)
        limit = query.get('limit',10)
        try:
            user_id = int(query.get('user_id',0))
        except Exception as e:
            return dict(code = 2, msg = '参数错误')

        PH_d = TM.persHonor(user_id,offset, limit)
        datas = []
        for Ph in PH_d:
            if isinstance(Ph.get('create_time'),datetime.datetime):
                event_id = Ph.get("event_id")
                event_d = TM.select('hot_event', dict(id= event_id), field = [' id,events_title, game_id,event_type_id '])
                datas.append(dict(create_time = Ph.get('create_time').strftime("%Y-%m-%d"),
                                    rank  = Ph.get('rank'),
                                    event_title = event_d.get("events_title"),
                                    game_icon = app_setting.QINIUHOST + GetGameData(True).get(event_d.get('game_id')),
                                    event_type_name = GetEventType().get(event_d.get('event_type_id')),
                                    event_id= event_id
                    ))

        return dict(code=0, datas = datas)  


## 电竞学院预约
class CollegeAppointment(Resource):
    def post(self):
        query = request.json
        user_id  = int(query.get('user_id'))
        token = query.get("token")
        if not user_id or not token or not tken.verify_auth_token(token) or user_id!=int(tken.verify_auth_token(token).get('id')):
            return dict(code = 30003, msg = '请登陆')
        check_d = TM.select('college_appointment', dict(user_id = user_id))
        if check_d:
            return dict(code =1, msg ='已经预约过')
        if TM.add("college_appointment",dict(create_time = datetime.datetime.now(), user_id = user_id)):
            return dict(code=0,msg = '预约成功')
        return dict(code=1, msg = '预约失败')
## 网易易盾图片验证和发送验证码
class PhoneQuickeck(Resource):
    def post(self):
        query = request.json
        validate = query.get('img_validate')
        mobile=query.get('mobile')
        _type  = query.get("type")
        if checkphone(mobile) is False:
            return dict(code = 30005, msg = '手机号码格式错误')
        ## 手机直接登陆
        msg =check_image_authcode(validate)
        if msg!='':
            return dict(code= 30006, msg ='图片识别错误，请重试')
        now = datetime.datetime.now()
        year_month = int(str(now.year) + str(now.month)+ str(now.day))
        auth_code =  randomNum(6)
        __business_id = uuid.uuid4()
        res = sms_send.send_sms(__business_id,mobile,"聚友校",'SMS_120130427',json.dumps(dict(code =auth_code )))
        res = json.loads(res)
        if res.get("Code")==u'OK':
            last_id = TM.add("sms_record", dict(
                                    create_time = now,
                                    code = auth_code,
                                    phone = mobile,
                                    business_id = __business_id,
                                    type= _type,
                                    year_month = year_month

                ))
            if last_id:
                return dict(code = 0 , last_id = last_id)
        elif res.get("Code")=='isv.BUSINESS_LIMIT_CONTROL':
            return dict(code=30008, msg  = '获取过于频繁!')
        return dict(code= 30008, msg ='获取验证码失败')

## 手机快速登陆接口
class phonequicklogin(Resource):

    def post(self):
        query = request.json
        mobile  = query.get('mobile')
        VerificationCode  = query.get('VerificationCode')
        if not checkphone(mobile):
            return dict(code=30005, msg = '手机号码格式错误')
        if not VerificationCode:
            return dict(code = 30006, msg = '验证不能为空')
        _last_id = query.get('last_id')
        ## 验证手机和验证码

        ## 数据写数据库

        check_code_d = TM.select('sms_record', dict(id = _last_id))


        if str(mobile)!= check_code_d.get('phone') or int(VerificationCode)!=int(check_code_d.get('code')) or check_code_d.get("type")!=1:
            return dict(code = 30009, msg = '验证码错误')

        if check_code_d.get('status')!=0:
            return dict(code= 30009, msg = '验证码无效')

        if (datetime.datetime.now() - check_code_d.get("create_time")).seconds >5*60:
            TM.update('sms_record',dict(status = 2), dict(id = _last_id))
            return dict(code = 30009, msg = '验证码过期')
        check_d = TM.select('user_auths',dict(identity_type = 'phone',identifier = mobile))
        if check_d:
            user_id = check_d.get('user_id')
            TM.update('sms_record',dict(status = 1), dict(id = _last_id))
            return dict(code = 0, token = tken.generate_auth_token(user_id), user_id = user_id)
        ## 不存在注册用户
        nickname ='yz_' + randomStr(10)
        last_id = TM.add('users',dict(
                                        nickname =nickname,
                                        icon = '43be3979862b20c607a7cbb4b0ef85da6.jpg',
                                        phone = mobile,
                                        create_time = datetime.datetime.now()

            ))
        if last_id:
            auth_id=TM.add("user_auths",dict(
                                            nickname = nickname,
                                            identity_type = 'phone',
                                            identifier = mobile,
                                            user_id = last_id,
                                            create_time = datetime.datetime.now()
                ))
            if auth_id:
                TM.update('sms_record',dict(status = 1), dict(id = _last_id))
                return dict(code = 0 ,token = tken.generate_auth_token(last_id), user_id = last_id)
            TM.delete('users',dict(id = last_id))

        return dict(code= 30008, msg ='系统繁忙！稍后重试')

## 平台用户登陆
class Login(Resource):

    def post(self):
        query = request.json
        phone = query.get('user')
        pwd = query.get('passWord')
        if checkphone(phone) is False:
            return dict(code = 30006, msg = '手机格式错误')

        ## 查看salt是否存在
        check_s = TM.select('user_auths',dict(identity_type = 'phone',identifier = phone), field = [' user_id, credential  '])
        if not check_s:
            return dict(code=30007, msg ='用户不存在')

        user_id = check_s.get('user_id')
        salt_d  =  TM.select('user_salt',dict(user_id = user_id), field = [' salt '])
        _credential = md5_value(str(pwd)+str(salt_d.get('salt')))
        if _credential!=check_s.get('credential'):
            return dict(code = 30009,msg= '密码错误')

        ip =  request.headers['X-Forwarded-For']
        if ip:
            ip = ip.split(',')[0]
        TM.add('login_record',dict(user_id = user_id, ip = ip,
            create_time = datetime.datetime.now()))
        return dict(code = 0, token = tken.generate_auth_token(user_id), user_id = user_id)





## 用户注册
class authRegist(Resource):
    def post(self):
        query = request.json

        mobile  = query.get('mobile')
        passwd = query.get('passWord')
        code = query.get('VerificationCode')
        _last_id = query.get('_last_id')

        ## 查看用户是否存在
        check_d = TM.select('user_auths',dict(identity_type = 'phone',identifier = mobile))
        if check_d:
            if _last_id:
                TM.update("sms_record",dict(status =2), dict(id =_last_id ))
            return dict(code = 30007, msg = '用户已存在')
        check_code_d = TM.select('sms_record', dict(id = _last_id))

        if str(mobile)!= check_code_d.get('phone') or int(code)!=int(check_code_d.get('code')) or check_code_d.get("type")!=0:
            return dict(code = 30009, msg = '验证码错误')

        if check_code_d.get('status')!=0:
            return dict(code= 30009, msg = '验证码无效')

        if (datetime.datetime.now() - check_code_d.get("create_time")).seconds >5*60:
            TM.update('sms_record',dict(status = 2), dict(id = _last_id))
            return dict(code = 30009, msg = '验证码过期')

        salt = randomStr(10)
        nickname = 'yz_' + randomStr(10)


        last_id = TM.add('users',dict(
                                        nickname =nickname,
                                        icon = '43be3979862b20c607a7cbb4b0ef85da6.jpg',
                                        phone = mobile,
                                        create_time = datetime.datetime.now()

            ))
        if last_id:
            salt_id = TM.add('user_salt', dict(user_id = last_id, salt = salt,create_time  = datetime.datetime.now()))
            if not salt_id:
                TM.delete('users',dict(id = last_id))
                return dict(code=30008, msg = '系统繁忙！稍后重试')
            auth_id=TM.add("user_auths",dict(
                                            nickname = nickname,
                                            identity_type = 'phone',
                                            identifier = mobile,
                                            user_id = last_id,
                                            create_time = datetime.datetime.now(),
                                            credential = md5_value(passwd+salt)
                ))
            if auth_id:
                TM.update("sms_record",dict(status =1), dict(id =_last_id ))
                return dict(code = 0 ,token = tken.generate_auth_token(last_id), user_id = last_id)
            TM.delete('users',dict(id = last_id))

        return dict(code=30008, msg = '系统繁忙！稍后重试')

## 微信分享
class WXShare(Resource):

    def post(self):
        query = request.json
        access_token = wx_op.wx_accesstoken(TM.r)
        if not access_token:
            return dict(code=1 ,msg = '获取token失败')
        ticket  = wx_op.getjsapiticket(TM.r,access_token)
        if not ticket:
            return dict(code=1 ,msg = '获取ticket失败')

        ## 地址
        url = query.get("url")
        event_id  = query.get("event_id",0)
        team_id = query.get("team_id",0)
        timestamp = int(time.time())

        _randomStr = randomStr(10)

        ret = dict(noncestr = _randomStr,
                jsapi_ticket = ticket,
                timestamp = timestamp,
                url  = url
            )

        _string = '&'.join(['%s=%s' % (key.lower(), ret[key]) for key in sorted(ret)])
        sha1 = hashlib.sha1()
        sha1.update(_string.encode("utf-8"))
        signature = sha1.hexdigest()
        e_data =dict()
        if event_id:
            e_data = TM.select("hot_event",dict(id = event_id), field = [ ' events_title, introduce,icon ' ])

        elif team_id:
            e_data = TM.select("game_team",dict(id = team_id), field = [ ' team_name as events_title, team_details as introduce, team_icon as icon '])
        if e_data:
            e_data['icon'] = app_setting.QINIUHOST + e_data['icon']
        return dict(code=0, data = dict(
                                    appid = app_setting.WX_APPID,
                                    noncestr = _randomStr,
                                    timestamp = timestamp,
                                    url = url,
                                    signature = signature

            ),e_data = e_data)

## 绑定第三方平台
class bingauth(Resource):
    def post(self):
        ## 用户注册
        ## 根绝类型来判断如何注册例如:type为phone
        ##  目前只有第三方授权登陆
        query  = request.json
        yz_log.info(query)
        _type = query.get('type')
        code= query.get("code")
        user_id = query.get("user_id",'')
        token = query.get("token","")
        if not user_id or not token or not tken.verify_auth_token(token) or int(user_id)!=int(tken.verify_auth_token(token).get('id')):
            return dict(code=1, msg = '请登陆')
        if  _type not in ['phone','zhifubao'] and (not code or code =='null'):
            return dict(code= 1, msg ='授权失败')

        ## 查看用户信息
        user_d = TM.select('users',dict(id  = int(user_id), status = '\x00'), field = [' id , phone'])
        if not user_d:
            return dict(code=30006, msg = '用户不存在')
        ## 查看用户绑定的第三方平台
        user_id = int(user_d.get("id"))
        user_auth_d = TM.select_all("user_auths",dict(user_id = int(user_id) ,status = '\x00'), field = [' identity_type '])
        auth_list = []
        for u_au in user_auth_d:
            auth_list.append(u_au.get("identity_type"))
        if _type in auth_list:
            return dict(code = 30008, msg  = '已有绑定的其他的账号')

        if _type=="phone" or _type=="zhifubao":
            if _type=='zhifubao':
                nickname=query.get('nickname',"")
                if not nickname:
                    return dict(code = 30005 ,msg = '真实姓名不能为空')
            mobile = query.get("mobile")
            VerificationCode = query.get("authcode")

            phone_d = TM.select("user_auths",dict(identity_type=_type,
                identifier = mobile))
            if phone_d:
                return dict(code = 30006, msg = '已被绑定在其他账号')

            check_code_d = TM.select('sms_record', dict(code = int(VerificationCode)))
            if str(mobile)!= check_code_d.get('phone') or int(VerificationCode)!=int(check_code_d.get('code')) or check_code_d.get("type")!=3:
                return dict(code = 30009, msg = '验证码错误')

            if check_code_d.get('status')!=0:
                return dict(code= 30009, msg = '验证码无效')

            if (datetime.datetime.now() - check_code_d.get("create_time")).seconds >5*60:
                TM.update('sms_record',dict(status = 2), dict(id = check_code_d.get("id")))
                return dict(code = 30009, msg = '验证码过期')
            if _type=='phone':
                if not user_d.get("phone"):
                    TM.update("users",dict(phone = mobile), dict(id = user_id))
                nickname = 'yz_' + randomStr(10)
            _id =  TM.add('user_auths',dict(create_time = datetime.datetime.now(),
                                    user_id = user_id,
                                    identity_type = _type,
                                    identifier = mobile,
                                    nickname = nickname
                ))
            if _id:
                TM.update("sms_record",dict(status = 1), dict(id = check_code_d.get("id")))
                return dict(code  = 0, msg = '绑定成功')
            return dict(code = 1, msg = '绑定失败')               
        elif _type =='wx':

            try:
                response  = requests.get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx2535ac9f0488e2bf&secret=81f8fd00417f6458bd0d8db010950f0a&code="+code+"&grant_type=authorization_code")
                content = json.loads(response.content)

                #用户的access_token
                access_token = content.get("access_token")
                #用户wx的openid
                openid = content.get("openid")

            except Exception as e:
                yz_log.error(str(e))

            try:
                response = requests.get("https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid)
                content = json.loads(response.content)
                #wx的nick_name
                nick_name = content.get("nickname")
                unionid = content.get("unionid")
                WX_d = TM.select('user_auths',dict(identity_type='wx',
                identifier = unionid))
                if WX_d:
                    return dict(code  = 0, msg = '已被绑定在其他账号')
                _id =  TM.add('user_auths',dict(create_time = datetime.datetime.now(),
                                        user_id = user_id,
                                        identity_type = 'wx',
                                        identifier = unionid,
                                        nickname = nick_name,
                                        credential = access_token
                    ))
                if _id:
                    return dict(code  = 0, msg = '绑定成功')
                return dict(code = 1, msg = '绑定失败')                

            except Exception as e:
                yz_log.error(str(e))
        elif _type =='qq':
            if query.get("code") != "null":
                code = query.get("code")
                try:
                    response  = requests.get("https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=101485201&client_secret=2faed734e5bdfe0ca810ca4349e0ba6d&code="+code+"&redirect_uri=http%3a%2f%2fgzb.dev-juyouxiao.com%3a9088%2findex.html")
                    yz_log.error(response.content)
                    content = response.content.decode("utf-8")
                    content = content.split("&",1)
                    content = content[0].split("=",1)
                    #用户的access_token
                    access_token = content[1]
                except Exception as e:
                    yz_log.error(str(e))
                    return dict(status=1,msg=str(e))

                try:
                    response = requests.get("https://graph.qq.com/oauth2.0/me?access_token="+access_token)
                    content = response.content.decode("utf-8")
                    content = content.split('"openid":"',1)
                    content = content[1].split('"}',1)

                    #用户QQ的openid
                    openid = content[0]
                except Exception as e:
                    yz_log.error(str(e))
                    return dict(status=1,msg=str(e))
                try:
                    ## 
                    QQ_d = TM.select('user_auths',dict(identity_type='qq',
                        identifier = openid))
                    if QQ_d:
                        return dict(code= 30006, msg = '已绑定在其他账号下')
                    response = requests.get("https://graph.qq.com/user/get_user_info?access_token="+access_token+"&oauth_consumer_key=101485201&openid="+openid)
                    content = response.content.decode("utf-8")
                    content  = eval(content)
                    #用户QQ的nickname
                    nickname = content.get("nickname")

                    _id =  TM.add('user_auths',dict(create_time = datetime.datetime.now(),
                                            user_id = user_id,
                                            identity_type = 'qq',
                                            identifier = openid,
                                            nickname = nickname,
                                            credential = access_token
                        ))
                    if _id:
                        return dict(code  = 0, msg = '绑定成功')

                    return dict(code  = 30006, msg='绑定失败')
                except Exception as e:
                    yz_log.error(str(e))
                    return dict(status=1,msg=str(e))

            else :
                return dict(status=1,msg="获取不到code")
        elif _type =='baidu':
            yz_log.info(query)
            if query.get("code") != "null":
                code = query.get("code")
            try:
                response = requests.get("https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&client_id=BaqV85SxU8ub0YmfxXmAoi6X&client_secret=hlUzDxcY4GqjEa9k8NCfrbzYvh1n8ML8&code="+code+"&redirect_uri=http%3a%2f%2fgzb.dev-juyouxiao.com%3a9088%2findex.html")
                content = json.loads(response.content)
                
                #用户的access_token
                access_token = content.get("access_token") 
            except Exception as e:
                yz_log.error(str(e))
                return dict(status=1,msg=str(e))

            try:
                
                response = requests.get("https://openapi.baidu.com/rest/2.0/passport/users/getInfo?access_token="+access_token)
                content = json.loads(response.content)
                #用户的userid
                userid = content.get("userid")
                #用户的username
                username = content.get("username")


                ## 查看是否已经授权登陆过
                baidu_d = TM.select("user_auths", dict(identity_type = 'tieba', identifier = userid))

                if baidu_d:
                    return dict(code  = 30005, msg  = '已绑定在其他账号下')
                _id =  TM.add('user_auths',dict(create_time = datetime.datetime.now(),
                                        user_id = user_id,
                                        identity_type = 'tieba',
                                        identifier = userid,
                                        nickname = username,
                                        credential = access_token
                    ))
                if _id:
                    return dict(code  = 0, msg = '绑定成功')
                return dict(code  = 0, msg = '绑定失败')                                
            except Exception as e:
                yz_log.error(str(e))
                return dict(status=1,msg=str(e))
        elif _type =="zhifubao":
            pass

        return dict(code =1, msg  = '未知登陆')




class carouselevent(Resource):

    def get(self):
        query = request.values
        offset = query.get("offset",0)
        limit = query.get("limit",4)
        car_d = TM.select_all('carousel', dict() , field = [ 'type, carousel_event_id, icon' ] ,offset = int(offset), limit = int(limit))         
        datas = []
        for car in car_d:
            if car.get("icon"):
                datas.append(dict(
                               type = car.get("type"),
                               icon = app_setting.QINIUHOST + car.get("icon"),
                               car_e_id =car.get("carousel_event_id") 

                    ))
        del car_d
        return dict(code=0 ,datas = datas)

class news(Resource):

    def get(self):
        query = request.values
        news_id = query.get("news_id")
        try:
            news_id = int(news_id)
        except Exception as e:
            return dict(code = 30005, msg = '参数错误')


        new_d = TM.select("news",dict(id = news_id), field = [' title, content, create_time, icon'])
        if new_d:
            new_d['create_time'] = new_d.get("create_time").strftime("%Y-%m-%d %H:%M:%S")
            return  dict(code = 0 ,data = new_d)
        return dict(code=30006, msg = '没有相应的新闻')

class QuestionsAsked(Resource):
    def get(self):
        quest_d = TM.select_all("questions_asked", dict(), field = [' content '] ,order_by = ' order by  priority ')
        return dict(code = 0, datas = quest_d)


## 关注平台接口
class FocusOnWe(Resource):
    def post(self):
        query =request.json
        try:
            user_id = int(query.get("user_id"))
            token = query.get("token")
        except Exception as e:
            return dict(code = 30005, msg = '参数错误')
        if not user_id or not token or not tken.verify_auth_token(token) or user_id!=int(tken.verify_auth_token(token).get("id")):
            return dict(code = 30006, msg = '请登陆')
        user_d = TM.select('users',dict(id = user_id), field = ['id'])
        if not user_d :
            return dict(code = 30007, msg = '用户不存在')
        if TM.select("user_focus",dict(user_id = user_id), field = [' id ']):
            return dict(code=30008, msg = '已关注')
        if TM.add("user_focus",dict(user_id = user_id, create_time = datetime.datetime.now())):
            return dict(code = 0, msg ='关注成功')
        return dict(code = 1, msg = '关注失败')

## 获取某个赛事的赛程安排表
class EvnetRaceCourse(Resource):

    def get(self):
        query = request.values
        event_id = query.get("event_id")
        ## 查看赛事是否存在
        event_d = TM.select("hot_event",dict(id = event_id),field =[' id '])
        if not event_id:
            return dict(code = 30006, msg = '非法操作')
        ## 对抗类赛事
        event_match_d = TM.EventMatch(event_id)
        ## 淘汰赛数据
        knockout_d = dict()
        ## 积分
        integral_d = dict()
        ## 决赛
        final_d = dict()
        
        return dict(code = 0, msg = 'test')


## 设置单场比赛的开始时间和赔率
class startEvent(Resource):

    def post(self):
        pass
